test​​​​​​​​​​​​​​​​​​​​​​​ And this j...">

JQuery attr returns 0 instead of value

So I have a very simple html:

<ul> <li value="test">test</li> </ul>​​​​​​​​​​​​​​​​​​​​​​​ 

And this jquery script

 alert($("li").attr("value")); 

It should return test , but it returns 0, why is this happening?

+4
source share
3 answers

If you want to return the text inside the li tag, follow these steps:

 alert($("li").text());​ 

You cannot use the value attribute (the value attribute in the li tag can only be numeric). Rename it to data value:

 alert($("li").attr("data-value"));​ 
+6
source

Basically, your selector captures every li element that you have. You might want to make your selector more specific. For the first <li> you can use -

 $('li:first').attr('value'); 

Using the id attribute will be fine too.

Another thing that should be noted here is that you are trying to retrieve the value of an attribute named value, and not the actual textual content inside the element. If you want to get the attribute value, then you are on the right track. If you want to use content that you can try, use text() or html() .

If there are several elements that you want to process, you might consider using the $.each function.

 var liValues = []; $.each('li',function(index,value){ liValues.push(value.attr('value')); }); 
+1
source

This does not seem to work because value simply not a valid attribute for the li element. As you can see this example , changing the attribute name to rel makes your code work (although I don't think rel really ... is weird).

You might want to consider storing this data elsewhere. Perhaps using the data-* attributes.

 <ul> <li data-value="test">test</li> </ul>​​​​​​​​​​​​​​​​​​​​​​​ alert($("li").data("value")); 
+1
source

Source: https://habr.com/ru/post/1445332/


All Articles