Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Get Plain Text Beside an HTML Element using jQuery?

Tags:

html

jquery

dom

<span>
    <label for="305">
        <input type="checkbox" name="305" style="vertical-align: middle;" value="305" id="305"> Farming General
    </label>
</span>

How do I get text "Farming General" using jQuery. Please do not ask me to change HTML structure

like image 382
Aivan Monceller Avatar asked Jul 27 '10 01:07

Aivan Monceller


People also ask

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.

Can I use innerHTML in jQuery?

jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element.

How do I get text in HTML?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.


1 Answers

You can grab it using an ID selector, going to the .parent() and using .text() like this:

​$("#305").parent().text()
//or:
$("label[for='305']").text();

Though, IDs starting with a number aren't valid until HTML5, just be aware :)


You can also get it without jQuery, like this:

document.getElementById("305").nextSibling.nodeValue

Though you may want to trim it down with $.trim(), like this:

$.trim(document.getElementById("305").nextSibling.nodeValue)
like image 68
Nick Craver Avatar answered Oct 04 '22 00:10

Nick Craver