1

I have some script written using the jQuery framework.

var site = {
link: $('#site-link').html()

}

This gets the html in the div site-link and assigns it to link. I later save link to the DB.

My issue is I don't want the html as I see this as being to dangerous, maybe?

I have tried:

 link: $('#site-link').val()

... but this just gives me a blank value.

How can I get the value inside the div without any markup?

GrantU
  • 6,325
  • 16
  • 59
  • 89

6 Answers6

2

Try doing this:

$('#site-link').text()

From the jQuery API Documentation:

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

Piet van Dongen
  • 1,629
  • 10
  • 13
2

Use the .text() jquery method like this:

    var site = {
        link: $('#site-link').text()
    }

Here is an example of what .val(), .html() and .text() do: jsfiddle example

97ldave
  • 5,249
  • 4
  • 25
  • 39
1

Use the text() method.

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Use the .text() function of jQuery to get the only text.

var site = {
link: $('#site-link').text()

}
0

to avoid html, you will be required to use text() method of jquery.

var site = {
link: $('#site-link').text()

}

http://api.jquery.com/text/

Ganesh Bora
  • 1,133
  • 9
  • 17
0

If you are planning to store the result in the database and you are concerned about HTML, than using something like .text() rather than .html() is just an illusion of security.

NEVER EVER trust anything that comes from the client side!

Everything on the client side is replaceble, hijackable by the client rather easily. With the Tamper Data firefox plugin for example, even my mother could change the data sent to the server. She could send in anything in place of the link. Like malicious scripts, whole websites, etc...

It is important that before saving the "link" to the database you validate it on the server side. You can write a regex to check if a string is a valid url, or just replace everything that is html.

It's also a good idea to html encode it before outputting. This way even if html gets into your database, after encoding it will be just a harmless string (well there are other stuff to be aware of like UTF-7, but the web is a dangerous place).

Community
  • 1
  • 1
vinczemarton
  • 7,756
  • 6
  • 54
  • 86