'How to take div value through parent elements using jquery?
I need to take the text "UNIT01". How I can do this using JQuery or JS?
`<div id="unit">
<ul class="choices">
<li>
<div>UNIT01</div>
</li>
<li>
<div>UNIT02</div>
</li>
</ul>
</div>`
Solution 1:[1]
$( document ).ready(function() {
var txt = $('.choices li:first-child>div').text()
console.log( txt );});
Solution 2:[2]
This code will access the text inside that div by accessing the div through its parent elements.
var unit = document.getElementById("unit");
var list = unit.getElementsByTagName("ul")[0];
var items = list.getElementsByTagName("li")[0];
var div = items.getElementsByTagName("div")[0];
var text = div.innerHTML;
alert(text);
<div id="unit">
<ul class="choices">
<li>
<div>UNIT01</div>
</li>
<li>
<div>UNIT02</div>
</li>
</ul>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Poncy |
Solution 2 |