How to print element with querySelector - javascript

I have this list of elements:
<ul class="connected">
<li class="name">Alex</li>
<li class="name">Laura</li>
</ul>
How can I print the names? I've tried: connected.querySelector(".name") but prints the entire label: <li class = "name">Alex</li>.
I want to know how I can print only the names, 'Alex', for example.

You can access the innerText property of the element. Documentation
const names = document.querySelectorAll('.name');
for (let name of names) {
console.log(name.innerText);
}
<ul class="connected">
<li class="name">Alex</li>
<li class="name">Laura</li>
</ul>

you can also use textContent or innerHTML in this case as all innerText, textContent and innerHTML have similar functionality.
But there are some slight differences among them:
textContent property sets or returns the text content of the
specified node, and all its descendants.
innerText will not return the text of elements that are hidden with
CSS but textContent will return.
The innerHTML property sets or returns the HTML content (inner HTML)
of an element. So use them according to the need.
const names = document.querySelectorAll('.name');
for (let name of names) {
console.log(name.textContent);
}
for (let name of names) {
console.log(name.innerHTML);
}
<ul class="connected">
<li class="name">Alex</li>
<li class="name">Laura</li>
</ul>
and one more point to remember:
The textContent property is not supported in Internet Explorer 8 and earlier, and the innerText property is not supported in Internet Explorer 9 and earlier.

Related

How do you select in-line text with Jquery?

How can I select the text infront of the unordered list below?
<li class="foo">
How can I remove this text?
<ul class="bar">
<li>Link</li>
</ul>
</li>
I tried doing something like this:
$('ul.bar').previousSibling().remove();
But I think that would only work with another element, and I'm not entirely sure how to go about selecting text that isn't contained inside tags.
Is the solution you're looking for.
$('.foo').contents().filter(function(){
return (this.nodeType == 3);
}).remove();
Demo here
The nodeType property returns the node type, as a number, of the
specified node.
If the node is a text node, the nodeType property will return 3.
Non jQuery version:
Get the Parent Node. Get all the Children nodes of the Parent. Convert the collection of Nodes to an array. Loop through the array. Check the nodeType on every iteration. If the nodeType === 3 then it's a text node. Then delete it.
Array.prototype.slice.call(document.getElementById('parent_node_id_here').childNodes, 0).forEach(function (value) {
if (value.nodeType === 3) {
value.remove();
}
});
$(".foo").contents().get(0).remove()
or without jquery
document.getElementsByClassName("foo")[0].childNodes[0].remove()
Try
$(".foo").replaceWith($.parseHTML($(".foo").html()).slice(1));
$(".foo").replaceWith($.parseHTML($(".foo").html()).slice(1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="foo">
How can I remove this text?
<ul class="bar">
<li>Link</li>
</ul>
</li>

lastElementChild for selecting the last li in ul?

I'm trying to select the last item in
<ul id="list_1">
<li>Apple</li>
<li>Orange</li>
<li>Grape</li>
<li>Banana</li>
<li>Mango</li>
</ul>
so I made
var ul = document.getElementById("list_1");
var mango = ul.lastElementChild;
So far, the selection seems to be working. But I'm not sure if I used lastElementChild correctly. Would
var mango = ul.getElementsByTagName("li")[4];
be the proper one to use?
That use of lastElementChild is fine, it will always refer to the last element that's a direct child of the list.
ul.getElementsByTagName("li")[4] will always give you the fifth, which may not be the last (although it is in this case).
Beware, though, that if you need to support IE8, IE8 doesn't support lastElementChild. (IE9 and up do.) To include IE8, you can get the last element reliably like this:
var ul = document.getElementById("list_1");
var mango = ul.children[ul.children.length - 1];
Unlike childNodes, children only contains child elements and not other kinds of children (text nodes and such), and it's supported on IE8.

Custom attribute Not fetchable from li

I have following Code/Structure, what I am trying to do is to hide a div if a custom attribute matches. The problem at the moment is that I can't get the custom attribute as demonstrated in this code:
var elementToHide = 'file_type';
jQuery('#search-img-ctrl').each(function() {
var locationli = jQuery(this).find('li').attr(elementToHide);
alert(locationli);
alert(elementToHide); // I can't get the custom attribute
if (locationli != elementToHide) {
jQuery(this).find('.search-img-box').hide();
} else {
jQuery(this).find('.search-img-box').show();
}
});
And following is my HTML Structure.
<div id="search-img-ctrl" class="search-img-ctrl">
<div class="sampages" style="display: block;">
<div class="search-img-box sampageitems">
<a href="image_detail.php">
<img id="imageimage_array" width="277" height="206" src="upload/2014-05-02-14-05-512014-04-08-14-04-40000560_d.png" alt="">
</a>
<br>
<ul>
<li> Name </li>
<li>upload/2014-05-02-14-05-512014-04-08-14-04-40000560_d.png</li>
<li>identity </li>
<li>Modify</li>
<li latitude="null">Latitude</li>
<li>null</li>
<li longitude="null">Longitude</li>
<li>null</li>
<li model="null">model</li>
<li>null</li>
<li file_type="png">model</li>
<li>png</li>
<li> Image Size </li>
<li>11Kb</li>
</ul>
</div>
</div>
Ideally under html5 you should suffix your custom attributes with data- prefix. However, in your code to find the li that has specific attribute, use:
var locationli = jQuery(this).find('li[' + elementToHide + ']');
Here is a JSFiddle demonstrating this: http://jsfiddle.net/wANxV/
The main wrapper have id and class same value. This is not a good.
Put a numer or other after your id value (id="search-img-ctrl-1" etc) , then do each cycle on class not on id
JQuery.each('.search-img-ctrl');
Put attributes in your markup with 'data' prefix (as Satpal said) and other thig you can use directly the selector
var locationli = jQuery(this).find("li["+elementToHide+"]");
This code reads the attribute of the first found element, but it does not filter on it:
var locationli = jQuery(this).find('li').attr(elementToHide);
A filter might look something like this:
var locationli = jQuery(this).find('li')
.filter(function(){
return $(this).attr(elementToHide);
});
But obviously closure's method is much shorter. And keypaul is right, using data- prefix is the right way to store your own metadata on elements.
the answers to use li[' + elementToHide + '] are good ones, but to help you understand what you are experiencing
let's break down this line of code:
var locationli = jQuery(this).find('li').attr(elementToHide);
as you know, jQuery(this).find('li') returns all of the decendants of this which are li's, and in your example, there are 14 of these.
What does .attr() return when applied to a set of 14 elements?
I guess it could return an array, a concatenation, who knows?, but the writers of jQuery decided to just return the attribute corresponding to the first element in the set. In this case, you are calling .attr(elementToHide) on <li>Name</li>. This element does not have the "file_type" attribute, therefore, you get an empty string in return.
Here's a quick fiddle to illustrate: http://jsfiddle.net/pmn4/B9bqK/
to solve your problem, use either the techniques described by #keypaul and #closure or use jQuery's filter method

Get element by tag not working?

Here is a very simple question, why get element by tag in javascript doesn't work like get element by id?
Here is my code example:
http://codepen.io/vincentccw/pen/KvAfF
HTML
<ul>
<li>list</li>
<li>list</li>
<li>list</li>
<li>list</li>
<li>list</li>
</ul>
JavaScript
document.getElementsByTagName("li").style.color="red";
getElementsByTagName returns a collection of elements called HTMLCollection. Try the following:
var elem = document.getElementsByTagName("li");
for (var i = 0; i < elem.length; i++) {
elem[i].style.color="red";
}
getElementsByTagName() returns a collection of elements (in a HTMLCollection). To work on each element in this array, you can loop through the items.
whereas
getElementById() returns one DOMElement - which has style and other attributes.

How to get Value / Text of a List item Javascript

how can i get the Value / Text of a <li> item ?
I found on the internet much ways to get the value for a dropdown list.
But not for a <li> item.
This is what I have tried so far:
var listt = document.getElementById('content1');
var selectedvalue = [listt.selectedIndex].text;
You can use the innerText property for most browsers, but the textContent property for Firefox:
<ul>
<li id="myLi">Hello, world</li>
</ul>
var li = document.getElementById("myLi")
console.log(li.textContent || li.innerText);
Here is a fiddle to demonstrate.
If you are using jQuery (you say you are, but I see no evidence) it would be as simple as using the .text() function:
$("#myLi").text();
If your <li> contains HTML markup too, you may want that. In this case you need to use the innerHTML property:
document.getElementById("myLi").innerHTML;
Again, jQuery has it's own equivalent .html() which caters for all sorts of different browsers:
$("#myLi").html();
Assuming myLi is a reference to the <li> element you want to get the text of, it's as simple as:
myLi.innerText
Note that <li> elements don't have values, because they're not inputs. They have content which can be a string of text or HTML defining other page elements. If your <li> element contained other elements, and you wanted the HTML of those as a string, you could instead do:
myLi.innerHTML
What's the difference? Let's assume your HTML looked like this:
<li><span>Some text</span></li>
Then
console.log(myLi.innerHTML); // outputs: <span>Some text</span>
console.log(myLi.innerText); // outputs: Some text
I would just use innerHTML if your list item has an ID or class name and assuming there is no other html in your list item.
<ul>
<li class="list-item">Item1</li>
<li class="list-item">Item2</li>
<li class="list-item">Item3</li>
</ul>
<script>
var list = document.getElementsByClassName('list-item');
var listArray=[];
for (var i=0;i<list.length;i++){
listArray.push(list[i].innerHTML);
console.log(listArray[i]);
}
</script>
//output
Item1
Item2
Item3
You could also try using the textContent property perhaps or innerHTML for that matter if you wanna get plain text.
var li_item=document.getElementById('content1');
console.log(li_item.textContent)

Categories