Javascript getElementsByTagName - javascript

I'm trying to use the getElementsByTagName("a") method to get all the elements under a specific tag.
However, I don't want every anchor tag. How would I narrow it so I only select all the anchor tags under the the ul tag for "someListClass" name?
<ul class="someListClass"> <li><a href... /></li>... </ul>
I know in jQuery you can just select with $(".someListClass a").
How would I do it without using jQuery?

Give your ul an id and then use
<ul id="ulid" class="someListClass"> <li><a href... /></li>... </ul>
document.getElementById ( "ulid" ).getElementsByTagName ( "a" );
element.getElementsByTagName
elements = element.getElementsByTagName(tagName);
elements is a live NodeList of found
elements in the order they appear in
the subtree.
element is the element from where the
search should start. Note that only
the descendants of this element are
included in the search, but not the
element itself.
tagName is the qualified name to look
for. The special string "*" represents
all elements. For compatibility with
XHTML, lower-case should be used.

you can use
element.getElementsByTagName(tagName)
where element is the UL item... so grab the UL item then search against that. something like:
<ul class="someListClass" id="myList"> <li><a href... /></li>... </ul>
var theList = document.getElementById('myList');
var listItems = theList.getElementsByTagName('li');

you want getElementsByClassName http://www.quirksmode.org/blog/archives/2008/05/getelementsbycl.html
links = document.getElementsByClassName("someListClass")[0].getElementsByTagName("a")

Without a framework, I can think of no other way than going though each element manually and to iterate its parents. If one of them has the class "somelistClass", add it to the stack. Otherwise, not.
If you are looking for the children of a single element, phoenix's approach is the way to go.

Related

How can I get the value of span within a list using vanilla JavaScript?

I'm new to JavaScript and am having a tough time getting the value inside of span within a list. In my example below I want console.log() to return the string value of Active.
Also, I know I can directly get it by using, but want to avoid this as I need to get to the specific list first and then get the attribute value of the span. So example below is not what I'm looking for.
var x = document.querySelector('.checkout-form__step-text').innerText;
I've tried the following, but am not having any luck:
var thisStep1 = document.querySelector('.checkout-form__step--active').getAttribute('span')
console.log(thisStep1)
<li class = 'checkout-form__step checkout-form__step--active'>
<span class="checkout-form__step-text p3"> Active</span>
</li>
This should be your selector.
document.querySelector('.checkout-form__step--active span')
Please check the below snippet.
const thisStep1 = document.querySelector('.checkout-form__step--active span');
console.log(thisStep1.innerHTML)
<li class='checkout-form__step checkout-form__step--active'>
<span class="checkout-form__step-text p3"> Active</span>
</li>
For examples on using selectors, some useful links are:
Document.querySelector()
Document.querySelectorAll()
Locating DOM elements using selectors
Selectors
Attribute selectors
You are making a grave mistake. Selector .checkout-form__step--active does not contain the span attribute. And span is not an attribute, but a tag!
I have given two solutions. In the first solution, you get the content of the span tag, and in the second, you get the name of the span tag.
If I understand your question correctly, then you need to get the text of the span tag in the console. You can do it like this, using innerText, specifying the span tag in the selector when accessing. Like this:
('.checkout-form__step--active span')
var thisStep1 = document.querySelector('.checkout-form__step--active span').innerText;
console.log(thisStep1);
<li class = 'checkout-form__step checkout-form__step--active'>
<span class="checkout-form__step-text p3"> Active</span>
</li>
This is where you get the tag name using tagName:
var thisStep1 = document.querySelector('.checkout-form__step--active span').tagName;
console.log(thisStep1);
<li class = 'checkout-form__step checkout-form__step--active'>
<span class="checkout-form__step-text p3"> Active</span>
</li>

how to select parent of a parent?

the jstree looks something like this :
<ul>
<li id ="head" >TITLE
<ul>
<li id="body">BODY
<ul>
<li id="foot">FOOTER
</li>
</ul>
</li>
</ul>
</li>
</ul>
This is basically a tree with depth 3.
I just want to know if its possible to access the id "head" from the id " foot"
something like
jQuery(#foot).parent().parent();
or
jQuery(#foot).parent().parent.attr("id");
or something similar
IDs are supposed to be unique across your page, so you shouldn't have more than one element with the same ID, and hence you should be able to use just $('#head') to select it.
In your case, I suppose you want to use a class 'head', which could appear many times in your list.
The easiest way to achieve it would be using jQuery closest(). It finds the first parent matching given selector.
$('#foot1').closest('.head')
http://api.jquery.com/closest/
You could always use the parents method:
$('#foot').parents('#head');
Although, since the head has an ID, you could just look it up directly: $('#head')
You cold write:
$('#' + $('#foot').parent().parent().parent().parent().prop('id')).do something with head
Make sure to read about the difference between .prop() & .attr()
Assuming these are the only <ul> and <li> elements on the page.
$('#foot').parents('li:last').attr('id');
Should give you the id which is head.
parents() function lists the parents of element from closest to farthest. So the last li element will be the one with id head.
Fiddle here.

appending elements to a list

I am trying to append a list element dynamically to already existing list.
I've a list in the form,
<ul id="test">
<li class="testField">YYAAHOOOOOO<li>
</ul>
I am trying to add an extra item to this list using jQuery append or after...
What I did was:
$(".testField").after("<li class='testField'>TEST MESSENGER</li>");
Used after function as append did not work, the after function works fine first time as there is only one element with the class name testField, but as the list grows, the after function will add the list items to all elements present,
To make it clear, on first trial I will get an output:
<ul id="test">
<li class="testField">YYAAHOOOOOO<li>
<li class='testField'>TEST MESSENGER</li>
</ul>
If I try the to add another element now for example <li class='testField'>GOOGLE</li>, the output will be like:
<ul id="test">
<li class="testField">YYAAHOOOOOO<li>
<li class='testField'>GOOGLE</li>
<li class='testField'>TEST MESSENGER</li>
<li class='testField'>GOOGLE</li>
</ul>
I thought about using ids, but I am trying to have an option to remove elements from the list too... So if I try to append to an undefined id, it will return error. Is there anyway to find the first element inside a list and append the element to that first one?
Try:
$(".testField:first").after("<li class='testField'>TEST MESSENGER</li>");
this will make sure that you are appending after the first element only
Alternatively, you could do this without jQuery:
var li = document.createElement('li'); // Create a List item.
li.setAttribute("class", "testfield"); // Set the li's class
li.addChild(document.createTextNode("Your Text Here!")); // Set the li's text
document.getElementById("test").addChild(li); // Append the li to the list
It's slightly more code, yes, but it's pretty much what jQuery does under the hood. (And faster, too)
If you want to add the new ul after the first li already in the list, replace the last line with:
var ul = document.getElementById("test");
if(ul.children.length > 1){ // If the list has 2 or more children (li's)
ul.insertBefore(li, ul.children[1]); // Insert the new item before the second item in the list.
}else{
document.getElementById("test").addChild(li);
}
Now, why am I posting a answer that requires more code?
Anything that can be done in jQuery can be done in native JS. I think it's good to have multiple different answers available on SO, especially if they use different techniques to do the same thing. That way, users can chose for themselves: short'n easy (jQuery), or if they don't want to use the library, native code.

how to get value of HTML from jquery or javascript

I want to select the following three values from the HTML file either by Jquery or Javascript.
class "class1" href value
class "class1" inner text value (PersonA in the example code)
class "Title" inner text value (Accountant in the example)
How can I select all the data of li node by node as? I am lost :(
<ol id="result-set">
<li id="v-0">
<div class="result-data">
..
<h2>
<a class="class1" href="">PersonA</a>
</h2>
<dl class="basic">
<dt>Title</dt>
<dd class="title">Accountant</dd>
....
</dl>
</div>
</li>
<li id="v-1">
...
</li>
.....
To get "PersonA": $('#v-0 h2 a').html();
To get href of that link: $('#v-0 h2 a').attr('href');
To get "Accountant": $('#v-0 dl dd').html();
You can modify the id ("v-0") at the start of the selector to choose a particular "row" of your data set.
With jQuery, you can do something like this:
$("#result-set li").each(function() {
var $currentLi = $(this),
$class1link = $currentLi.find("a.class1"),
class1href = $classAlink.attr("href"),
class1content = $classAlink.html();
// do something with values
});
The .each() method will process each li element. Within the callback to .each() the variable $currentLi is a jQuery object holding that li (set from $(this) where this is the li element itself). The .find() method is used to find the anchor element within the li and then its href and content are retrieved.
The "Accountant" you asked about is one item in a definition list, so you'd probably want to loop through that list with another .each() statement nested inside the one above.
You don't make it clear how you want to use the values, but this should get you started. For further details about the various jQuery methods I've mentioned check the jQuery API.
document.getElementById(Id).value
returns value of element with specific id. in jquery:
$("#id").val()
by class $(".yourClass").val()
to get attribute value use attr("attributeName") for example $(".class1").attr('href').
if you want to get text from specified element use .text() like $(".title").text() //will return Accountant.
You mean selecting them with a jQuery selector? That would be done like so:
$('.class1').attr('href') //class1 href, i persume you dont mean classA as it doesnt exist in your code
$('.class1').text(); //PersonA text using the same selector
$('.title').text(); //Accountant from the .title dd

jQuery: take existing HTML, modify one node, then reinject

I have a blob of HTML that I'm retrieving using simple jQuery selectors, something like the following:
<div id="stuff">
<ul>
<li>some</li>
<li class="ninja">stuff</li>
</ul>
</div>
I'm basically doing:
var myblock = $("#stuff").html();
now I want to inject an additional li element to the bottom of that li list with very similar attributes to the li above it, but i want to change the class ninja to class samurai.
What's the best way of going about that with jQuery?
Simply select the <ul> and append the <li> to it
$("#stuff ul").append('<li class="samurai">stuff</li>');
If you actually wanted to copy the last <li> element, change the class then add to the list, then you could do something like this
var ul = $("#stuff ul");
ul.append(ul.find('li:last').clone().removeClass().addClass("samurai"));
pass true into clone() if you also want to copy event handlers too.
The problem with taking a whole chunk of HTML, changing an element and then reinserting is that any event handlers set up on elements that will be replaced when you reinsert the HTML will be lost, so it's more elegant/ and less cumbersome/intrusive to simply manipulate the part of the DOM that you need to.

Categories

Resources