How to select element based off specific parent structure in JS? - javascript

I am trying to write a script that will get the grab the only if the parent structure is div.main-element input+label+ul.
Is there any appropriate way to set that up using javascript or jquery?
If anyone could direct me to the appropriate answer or documentation that would be absolutely awesome.
My end goal would be to replace the ul>li with an hr tag using either an append or .replace()
here is my HTML:
<div class='main-element'>
<input>
<label></label>
<ul>
<li>Example</li>
</ul>
</div>
<div class='main-element'>
<input>
<label></label>
</div>

You could check if the element that you want exists using this kind of code in jquery :
if($("div.main-element ul li").length){
//your code
}
This will execute on your html example, next you can modify the value of the first element using :
$("div.main-element ul li").append("blahblahblah");
Note that this gives you access to the first li tag found inside of a div.main-element>ul of your html page.

You can provide a second argument to a jquery call that is the parent container within which you want to get elements from. There is also a find function that does the same thing.
HTML:
<div class='main-element'>
<input>
<label></label>
<ul>
<li>Example</li>
</ul>
</div>
<div class='secondary-element'>
<input>
<label></label>
</div>
JS:
var $secondaryElement = $('.secondary-element');
var $secondaryInput = $('input', $secondaryElement);
Another approach:
var $secondaryInput = $('.secondary-element').find('input');
Both of the examples above will return ONLY the input element inside of the secondary-element div.
Does that answer your question?
Links:
https://api.jquery.com/find/
and
https://api.jquery.com/jquery/#selector-context

This will get all elements with your composition and replace ul>li by hr.
var elements = document.querySelectorAll(".main-element input+label+ul li");
for(var i = 0; i < elements.length; i++){
var parent = elements[i].parentNode.parentNode;
var ul = elements[i].parentNode;
ul.parentNode.removeChild(ul);
var hr = document.createElement("hr");
parent.appendChild(hr);
}

Related

Select child element from parent - Plain Javascript

I need some help with Javascript.
What I try to do is move an element to another element.
Normaly I can use the queryselector but in this case I can not because there are multiple elements with the class "destination". To get the result what I want I need select first the parent element "catalog-item" and after that the child "destination".
I need some help to get the right element catalog-item->destination
<div id="catalog-item">
<div class="destination">
</div>
</div>
<div id="move"></div>
<script type="text/javascript>
var itm = document.getElementById("move");
var cln = itm.cloneNode(true);
itm.remove();
document.getElementById("catalog-item").children(".destination").appendChild(cln);
</script>
Who can help me?
You can select the child element with querySelector by writing document.querySelector("#catalog-item .destination"). Just put a space between them.

Using a variable value on multiple elements with the same iD

So I have a file like
<div class="u1">
<p id="level1"></p>
<p id="level2"></p>
</div>
<div class="u2">
<p id="level1"></p>
<p id="level3"></p>
</div>
and if I use something like
document.getElementbyId("level1").innerText(or innerHtml) = "Hello"
it writes that string on one element, and not on every element with id="level1"
I tried with
$('#level1').text("Hello");
but it works only for one.
I need something to write a string on every element with id="level1".
ID is a unique identifier, so you can't have few items with the same ID. Provided HTML code is invalid. You can use CLASS attribute or data-id or....
If you can't change HTML and it comes from third-party dependency, then we have a list of NOT recommended but WORKING solutions
jQuery:
$('[id="level1"]').text("Hello");
js:
var elements = document.querySelectorAll('#level1'); + for loop to iterate elements
And a lot of similar solutions based on knowledges how elements selecting works under the hood
It is ideal to have Unique Ids and thus you cannot update it this way. What you can do is you can give it a class like this:
<div class="u1">
<p id="level1" class="helloText"></p>
<p id="level2"></p>
</div>
<div class="u2">
<p id="level1" class="helloText"></p>
<p id="level3"></p>
</div>
Now use this JS to update the HTML:
var paras = document.getElementsByClassName("helloText");
for (i = 0; i < paras.length; i++) {
paras[i].innerHTML = "Hello";
}
You can also remove the Ids or make them unique to make your code cleaner. It is never recommended to use duplicate Ids.
You give a classname to the elements you need:
class = "levels"
in the script, use document.getElementsByClassName, which return an array with all elements. then you can loop through that array to get the info of each elements.
let levels = document.getElementsByClassName("levels");
for (let j=0; j<levels.length; j++){
levels[j] do something...;
}

Javascript adding a class to an element using the value from an onClick event

I have been trawling around all day trying to fix this issue I am sure it is simple but I will be darned if I can figure it out.
I have tried the archive and cannot seem to find the solution to my particular issue, so any help will be very gratefully received!
I am wanting to add a style to an individual element when a list item is clicked. The list Item Id's and associated div classes are created dynamically in my php code.
With my script I have got as far as getting an alert box appearing as a test to show that the onclick event attached to the list item is returning the correct value. In this case ID and class "1995"
However when I add the correctly returned value into my script using
document.getElementsByClassName(supplyClass).style.display = "none";
In the console I get
"Uncaught ReferenceError: reply_click is not defined"
Abridged code is below with the succesful alert line commented out.
function reply_click(supplyClass) {
//alert(supplyClass);
document.getElementsByClassName(supplyClass).style.display = "none";
}
<div class="supply-container">
<div class="supply-menu">
<ul>
<li id="1995" onClick="reply_click(this.id)">Desking Systems</li>
</ul>
<div>
<div class="supply-content-container">
<div class="1995 supply-content" >
<p>LorumIpsum</p>
</div>
</div>
</div>
As your event handler is passing id of clicked element you need to use document.getElementById to find the element and make the display to none as below
function reply_click(supplyClass)
{
alert(supplyClass);
//document.getElementsByClassName(supplyClass).style.display = "none";
document.getElementById(supplyClass).style.display = "none";
}
<div class="supply-container">
<div class="supply-menu">
<ul>
<li id="1995" onClick="reply_click(this.id)">Desking Systems</li>
</ul>
<div>
<div class="supply-content-container">
<div class="1995 supply-content" >
<p>LorumIpsum</p>
</div>
</div>
</div>
document.getElementsByClassName(supplyClass) returns list of elements so you can't set its style directly.
If you want to set style for all elements returned this way then you can do it like this.
const els = document.getElementsByClassName(someClass);
for (let i = 0; i < els.length; i++) {
els[i].style.display = 'none';
}
Thanks Felix & Sumeet The line of correct code that worked is as follows.
document.querySelector('.supply-' + supplyClass).style.display = 'none';
I had not realised you cannot start a class name with an integer so appended the word supply with a hyphen to the supplyClass value and it worked fine.
Thanks again.

How do I move these elements in DOM

I don't want to change HTML because I want to leave the display the way it is for default view and want to move them in second view. I want to know how I can dynamically order the class of a div.
I want to do this via button click. I have adEventListener() for 'click' where I am doing something and the move logic would go inside this event listener.
I understand that I can get these divs, remove from their parents and place it where I want. But I do not know how to do these for each of them since I have multiple lis. I am struggling with the loop so that I can do these for each li. I need to do this using pure JS and not jQuery.
<ul>
<li>
<div>
<div class="a">
<div class="b">
<a class="c">
<div class="d"></div>
<div class="e">
<div class="f"></div> // this is the first item that I want to move
</div>
<div class="g"></div> // this is the second item that I want to move
</a>
</div>
<div class= "h"></div> // I want above mentioned divs to be before this div
</div>
</div>
</li>
//There are multiples lis
<li></li>
Assuming you would like to do this on load of the page, you could solve your problem with the following JQuery DOM manipulations:
$(document).ready(function(){
$("ul .a").each(function(index, element){
$current_div_a = $(element);
$div_h = $current_div_a.find(".h");
$div_f = $current_div_a.find(".f");
$div_f.clone().insertBefore($div_h);
$div_f.remove();
$div_g = $current_div_a.find(".g");
$div_g.clone().insertBefore($div_h);
$div_g.remove();
})
});
You can test it out on this demo.
I strongly advise against this way of doing it though. I guess it's also the reason why your question got some downvotes too. Just modifying your HTML keeps your code clean, maintainable and clearer for anyone else starting to work on your project. Keeping backwards compatibility for your code as much as possible will cause maintainability problems later.
I ended up using
var list = document.querySelectorAll("ul li");
for (var item of list) {
let fClass = item.querySelector(".f");
fClass.parentNode.removeChild(fClass);
let parentOfFirstChildAfterWhichIwantMyF = item.querySelector(//selector for parentOfFirstChildAfterWhichIwantMyF);
parentOfFirstChildAfterWhichIwantMyF.insertAdjacentElement("beforeend", fClass);
}

Replace content of header tag based on its own existing content

dI have a pre-existing block of html I need to alter using jQuery. The HTML looks as follows:
<div class="main">
<div class="wms-column wms-column-nav">
<div class="wms-column-nav-body">
<div class="section">
<h3>Recent News</h3>
<ul class="other">
<li>Something</li>
</ul>
</div>
</div>
</div>
</div>​
I need to target the H3 and change its inner text. However, with no IDs, targeting it with selectors is tricky. There are many other H3 tags through their site that cannot be changes, but have the same selector path. How can I target this H3 based on its content, and then change it? I'd prefer a method that inserts html and not text, as some special characters are going to be used.
Thanks!
In vanilla Javascript :
var elements = document.getElementsByTagName('h3');
for (var i=elements.length; i-->0; ) {
var element = elements[i];
var text = element.textContent || element.innerText;
if (text=='Recent News') {
element.innerHTML = 'some new text';
}
}
Demonstration
Using jQuery:
$('h3') will select all of the header tags. You can address them individually: $('h3').eq(0) $('h3').eq(1) etc.
You can also loop through them easily:
$('h3').each(function() {
alert(this.text()) <-- "this" will point to the current item in the loop.
})
Inside the loop you can access any of the current item's content, properties or attributes. You can base your logic on this accordingly.

Categories

Resources