How to detect element with DOM JavaScript? - javascript

I want to detect an element and change the backgroundColor through JavaScript but am having trouble with it.
I can't check for the element because it is a tag+class + tag+class...
Here's my code :
var one = document.getElementsByTagName("div");
var two = document.getElementsByClassName("red");
var three = document.getElementsByTagName("h2");
var four = document.getElementsByClassName("title");
one.two three.four.style.backgroundColor ="#00c497";
The format is "div.red h2.title".
How can I correctly detect an element using DOM JavaScript?

If you can, use querySelector for this:
document.querySelector("div.red h2.title").style.backgroundColor = "#00c497";
<div>
<h2>Don't Touch</h2>
</div>
<div class="red">
<h2>Don't Touch</h2>
<h2 class="title">Change</h2>
</div>

Related

jquery get p and span data and place in variables

<div class="pricecard aircraft">
<div class="card-body">
<p>One way<br>
<span class="onewayaircraftprice">£492.00</span></p>
</div>
</div>
How can I use jquery to use the data in the p tag in to 2 variables?
ie
var1 = "One Way"
var2 = "£492.00"
my code
// This returns both data :(
var1 = $(this).children('.card-body').find('p').text());
First option is to wrap one way by any tag. Then it's simple. Eg. span:eq(0) and span:eq(1).
// This returns both data :(
var span = $('.card-body').find('span:eq(1)').text();
var text = $('.card-body').find('span:eq(0)').text();
console.log(span)
console.log(text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricecard aircraft">
<div class="card-body">
<p><span>One way</span><br>
<span class="onewayaircraftprice">£492.00</span></p>
</div>
</div>
With your current HTML markup you can use for example this one
// This returns both data :(
var span = $('.card-body').find('span').text();
var text = $('.card-body').find('p').text().replace(span, '');
alert(text); // One way
alert(span); // £492.00

Exclude multiple elements from a DOM query using a variable

I have this HTML:
<div class="elem">
</div>
<div class="elem-1">
</div>
<div class="elem-2">
</div>
<!--Select the ones below-->
<div>
</div>
<p class="other-class">
</p>
I have this code:
var elems = document.querySelectorAll(".elem, .elem-1, .elem-2[,...]");
var otherElems = document.querySelectorAll(":not..."); //can I reuse elems here?
Can I use the elems variable to select all elements except for the ones in elems?
EDIT: This seems like code duplication:
var foos1 = document.querySelectorAll(".bars1, .bars2, .bars3, #bar1, #bar2[,...]");
var foos2 = document.querySelectorAll(".bars-1, .bars-2, .bars-3, #bar-1[,...]");
var foos3 = ...
.
.
.
var foosN
//list all former elements again
var noFoos = document.querySelectorAll(":not(.bars1, ..., .bars-3, #bar-1......)");
Instead I would like to reuse the variables I stored these elements in already.
Something like:
var noFoos = document.querySelectorAllBut(foos1, foos2, foos3,...);
You could put the first selector inside the not:
var elements = document.querySelectorAll(".elems, .elems-more, .elems-more-more[,...]");
var otherElements = querySelectorAll("div:not(.elems, .elems-more, .elems-more-more[,...])");
Also, you could put the selector in a variable to avoid duplication. This might not be the most efficient solution, though.

How to append an element before another using Javascript?

I tried following the a wiki and looking into multiple questions here but I still have problems with insertBefore..
This is my sample:
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
<script>
topbar = document.getElementsById("container");
boardlist = document.getElementsById("first");
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML("0");
topbar.inserBefore(bmcontainer, boardlist);
</script>
I want to append the span#zero before the span#first. What am I doing wrong? I'm trying to not use jQuery, so I'm looking for a totally javascript solution.
Node.insertBefore() is the answer.
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
If you have Parent Node, then you should use ParentNode.prepend()
ParentNode.prepend(nodesToPrepend);
Take a look # mentioned links for full documentation and examples.
Update
You have some issues in your code (typo and wrong usage of innerHTML), here is fixed code.
HTML
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
JS
var topbar = document.getElementById("container"),
boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML = "0"; // innerHTML is not a function, it's a property
topbar.insertBefore(bmcontainer, boardlist);
jsfiddle
Notice that InnerHTML is not a function, it's a property, read more about that here: Element.innerHTML
Prepend pure javascript
MDN article on insertBefore()
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
Source: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend
Also, the jQuery prepend() Method
You can read about it here and here.
You can use the insertAdjacentElement function.
var boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
boardlist.insertAdjacentElement('beforebegin', bmcontainer);
Element.insertAdjacentElement

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

Javascript: Get div inside of div

I have two divs nested like so:
<div id="upper">
<div id="lower" name="moo">
</div>
</div>
How would I, using jQuery or JavaScript alone, can I get the name of that lower nested div?
var nameValue = $('#lower').attr('name');
But if you really want to use the outer div to select the inner one:
var nameValue = $('#upper > div').attr('name');
Or
var nameValue = $('#upper #lower').attr('name');
Or
var nameValue = $('#upper').find('#lower').attr('name');
Use .children.
http://api.jquery.com/children/

Categories

Resources