I am new to this and I have this element and I have to somehow "get it". There are few more element above it, there's just an element I need:
<a class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
Thanks for help!
$('a.btn_green') will return an array of you could use the Array index to access the proper value if the index is known and does not change
var $a = $('a.btn_green');
var el = $a[2];
You can use getElementsByClassName.
document.getElementsByClassName('btn_green')
This will return an array of all the elements that match. If you have only one element you can access it at index 0.
document.getElementsByClassName('btn_green')[0]
If you added an ID to the element,and then use getElementById
<a id="YOUR_ID_HERE" class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
document.getElementById('YOUR_ID_HERE')
You can do something like this in standard JS you would do something similar to this:
var button = document.getElementsByClassName('btn_green');
If you're just looking to get that specific element I would suggest adding an id
<a class="btn_green" id="myButton" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
And here is the JS
var button = document.getElementById('myButton');
Details are commented in the Snippet. The anchor in OP's code is atrocious so I made the markup simpler, but the code provided here will work an any anchor(s) under certain conditions described below.
SNIPPET
/* Plain JavaScript */
/* If there is only one element that has the class="btn_green" */
// By className
var btnByClassName = document.querySelector(".btn_green");
/* If it is the only link (anchor)
*/
// By tagName
var btnByTagName = document.querySelector("a");
/* If theres more than one element with the class="btn_green" */
// By className
var btnsByClassName1 = document.querySelectorAll(".btn_green");
// or
var btnsByClassName2 = document.getElementsByClassName("btn_green");
/* The two methods above will collect all elements with the
specified className. The group of elements collected is known
as a HTML Collection or NodeList. If you need to specifically
target one of them out of a group, say like the 2nd one, you have
to count from 0. Ex. the second element in a NodeList would be 1.
*/
/* Continuing from the previous example above, we can single out a
single element by placing the 0 count number of that element:
*/
var btnsByClassNameA = document.querySelectorAll(".btn_green")[1];
//or
var btnsByClassNameB = document.getElementsByClassName("btn_green")[1];
/* A different type of NodeList/HTML Collection can be had by
targeting the tagName, this example we are targeting the first
anchor:
*/
var btnsByTagName1 = document.querySelectorAll("a")[0];
//or
var btnsByTagName2 = document.getElementsByTagName("a")[0];
/* Note: Although these methods are able to get a group of
elements, they are able to get an element if it is the only
one of it's kind by using [0].
*/
/* jQuery */
/* jQuery makes it easier and does most of the thinking for us.
You must make sure that your page has the jQuery library loaded.
Look at the HTML section below, you'll see a <script... tag. You
must have that tag inside the <head></head> or before the </body>
otherwise you code will not function.
*/
/* Note the variable has a $ prefix. This is optional and it's
purpose is to show other developers that the variable represents a
jQuery Object.
*/
// By className
var $btnsByClassName = $(".btn_green");
// By tagName
var $btnsByTagName = $("a");
/* This part is not part of the question, it is just to show that
these references are working */
$btnsByTagName.on('click', aTonOfStuff);
function aTonOfStuff() {
btnByClassName.style.backgroundColor = "black";
btnByTagName.style.color = "lime";
for (let i = 0; i < btnsByClassName1.length; i++) {
btnsByClassName1[i].style.fontSize = "40px";
btnsByClassName2[i].style.fontVariant = "small-caps";
}
btnsByClassNameA.style.backgroundColor = "#0E0";
btnsByClassNameB.style.color = "#000";
btnsByTagName1.style.lineHeight = "2";
btnsByTagName2.style.textDecoration = "overline";
$btnsByClassName.fadeOut("slow");
$btnsByTagName.fadeIn("slow");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click any link.</p>
<a class="btn_green" href="#/">First Green Button Anchor Link</a>
<a class="btn_green" href="#/">Second Green Button Ancor Link</a>
Something like $('a.btn_green') would "get" that <a> element but it is not guaranteed to get it uniquely. You may need to use something like the :nth-child pseudo-selector to do this if you cannot modify the source. Without more context it is impossible to say what a selector would be that would uniquely retrieve either the <a> or the <span> element.
Here is a jQuery tutorial and here is a CSS selector reference, just in case you need them.
Edit
One weird thing happening on the page is $ no longer seems to be bound to jQuery. They must be loading something which uses $ after jQuery which is causing selectors like $('a.btn_green') to return null. You can replace $ with jQuery instead.
I tried the using jQuery('.btn_green_white_innerfade.btn_medium') to find the element, but it looks like there are three elements on the page which share that selector. So I looked further up in the source and found that the button I think you want is within a div with the id market_buyorder_info. This led me to the following code to get the element uniquely:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium')
And this code to trigger a click in the console:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium').click()
Related
I'm trying to create a new div in Javascript with two spans in it, each containing a string of text. They are then meant to be inserted before div.two in div.inner.
The div I'm trying to insert it into only has a class and I cannot target it by any ID, unfortunately.
I have also created a codepen here: https://codepen.io/lisaschumann/pen/BXqJKY
Any help is massively appreciated!
HTML
<html>
<div class="inner">
<div class="one"></div>
<div class="two"></div>
</div>
</html>
JS
window.onload=function(){
var infobox = document.createElement("div");
infobox.classList.add('infobox');
var spanOne = document.createElement("div");
var spanOneText = document.createTextNode('Important text 1');
var spanTwo = document.createElement("div");
var spanTwoText = document.createTextNode('Important text 2');
spanOne.appendChild(spanOneText);
spanTwo.appendChild(spanTwoText);
infobox.appendChild(spanOne);
infobox.appendChild(spanTwo);
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
}
Errors:
Cannot read property '1' of undefined
at window.onload
The main issue is that getElementsByClassName returns a live collection of nodes rather than one node and so you would need to access the correct node in that list similar to an array: targetDiv[0], perhaps.
The easier method is to use querySelector to grab the element you want using its class, for example:
var parent = document.querySelector(".inner");
var two = document.querySelector(".two");
parent.insertBefore(infobox, two);
But! there's even a shortcut method you can use here that allows you to add an HTML string direct to the DOM which might save you a bit of time, and some code.
// Create the HTML
const html = `
<div>
<span>Text alpha</span>
<span>Text beta</span>
</div>`;
// Grab the element containing your "two" class
const two = document.querySelector('.inner .two');
// Using insertAdjacentHTML to add the HTML before the two element
two.insertAdjacentHTML('beforebegin', html);
<div class="inner">Inner
<div class="one">one</div>
<div class="two">two</div>
</div>
insertAdjacentHTML
This doesn't work because of these lines
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
document.getElementsByClassName returns a NodeList. targetDiv.childNodes is undefined, because childNodes doesn't exist on a NodeList.
You need to either use a list operation like Array.prototype.forEach, change getElementsByClassName to getElementByClassName (note the s) or access the first node in the node list using the array indexer syntax.
I assume you meant to do something like this:
var targetDiv = document.getElementByClassName('inner')
targetDiv.insertBefore(infobox, targetDiv.childNodes[1])
This will insert a node in between the first and second child of the first DOM node with the class inner.
Try this out , targetDiv is an array by default due to the getElementsByClassName method , even though it has a single element.Hence you need to specify the index i.e. 0 ( as it's the first element of the array)
var targetDiv = document.getElementsByClassName("inner")[0]; targetDiv.insertBefore(infobox, targetDiv.children[1]); }
Using JQuery
$(document).ready(function(){
$(`<div>Important text 1<span></span>Important text 2<span></span></div>`).insertBefore( ".inner .two" );
)
I would encourage you to use JQuery and then shift to vanilla javascript later on. You can do simple tasks like this in just few lines of code and it is also easily debuggable because of that
So I got into JavaScript and tried setting up the following scenario:
I have 2 Buttons on my Site (IDs are buttonWebdev and buttonUXUI), which should trigger an Action when they are hovered upon. If buttonWebdev is hovered upon, it should hide all p', h3's and imgs with the class "classWeb". I wrote this code to do it, but it doesn't work:
HTML:
<h3 class="classWeb">Editierbare Inhalte</h3>
<p class="classWeb">Test</p>
<button class="buttonImg" id="buttonWebdev"><img src="./img/buttonWebdev.png" /></button>
<script type="text/javascript">
var button = document.getElementById('buttonWebdev');
var classWeb = document.getElementsByClassName('classWeb');
button.onmouseover = function() {
classWeb.className = 'webdev';
}
CSS:
.classWeb.webdev {
display: none;
}
First, since there can be more than one element with a given class on a page, getElementsByClassName returns a list of elements instead of a single element. You’ll need to perform your action on every element of that list, with a for…of loop, for example:
for (let element of classWeb) {
element.className = 'webdev';
}
(for…of is relatively new, though, so you might have to use a regular for loop depending on your target browsers.)
After fixing this, you’ll run into another problem. When you assign to className like that, you’re setting the entire list of classes on an object. If the list of classes is 'webdev', it no longer includes 'classWeb'. Modern browsers support an API to add a class without affecting the rest:
for (let element of classWeb) {
element.classList.add('webdev');
}
The way to diagnose these sorts of problems is by opening up your browser’s developer tools, looking for JavaScript errors in the console, and looking at the state of the elements you’re trying to affect in the document tree.
document.getElementsByClassName('classWeb'); this gives collection & to add classes you need to iterate over them & then apply classes.
classWeb[0].className = 'webdev'; would reset class
either use classWeb[i].className += ' webdev'; or classWeb[i].classList.add('webdev');
See below working example
var button = document.getElementById('buttonWebdev');
var classWeb = document.getElementsByClassName('classWeb');
button.onmouseover = function() {
for (var i = 0; i < classWeb.length; i++)
classWeb[i].className += ' webdev';
}
.classWeb.webdev {
display: none;
}
<h3 class="classWeb">Editierbare Inhalte</h3>
<p class="classWeb">Test</p>
<button class="buttonImg" id="buttonWebdev">hover over me</button>
Firstly, the
document.getElementsByClassName('classWeb');
will give you a LIVE list of all the matched elements. That means that when you reassign the class like so:
classWeb[0].className = 'webdev';
the element will be removed from the list, as it no longer corresponds to the original command which was to find all elements with a specific class (which you overrode with 'webdev').
An easier and more friendly api is querySelectorAll which mimics the jQuery selector (which uses css selectors to find elements, thats why there is a # for an id and a . for a class name). The example below shows, how to use it.
var button = document.querySelector('#buttonWebdev');
var classWeb = document.querySelectorAll('.classWeb');
button.onmouseenter = function() {
for (var i = 0; i < classWeb.length; i++) {
classWeb[i].className = 'webdev';
}
}
ps. The querySelectorAll is not a live list, so items will not disappear after you change their class.
ps2. Use onmousenter instead of onmouseover as the onmouseenter is only called when the mouse starts hovering over an element, while onmouseover will be called on every mouse move over the element (even if already hovering).
Good luck!
I am trying to changing anchor, id, span or b tag text color, but it's not changing because of randomly changing id.
Here is the HTML Code:
<a id="XgP7Wrq-1503732157576" tabindex="-1" href="javascript:void(0);" style=""><span class="thin">here</span> <b>sometext</b></a>
Here is the JS Code:
var x = getElementsbyid("XgP7Wrq-1503732157576");
x.style.color = '#00FF00';
else if any alternative way to achieve this?
Thanks
If you are traversing the DOM with ID, the correct syntax is as follows,
var x = document.getElementById("XgP7Wrq-1503732157576");
x.style.color = "#00FF00";
You do not include the hashtag as argument because the method specifically looks for the ID.
Since the ID of the elements is always changing, you may do one of the followings too.
// Accessing the third <a> element
var x = document.getElementsByTagName("a")[2]
// Accessing the first element with class "apple"
var x = document.getElementsByClassName("apple")[0]
Try using the class
<a id="XgP7Wrq-1503732157576" class="myclass" tabindex="-1" href="javascript:void(0);" style=""><span class="thin">here</span> <b>sometext</b></a>
Code js:
var x = document.getElementsByClassName("myclass");
//for first anchor
x[0].style.color = "#00FF00";
//for all
for(var i=0; i<= x.length; i++)
{
x[i].style.color = "#00FF00";
}
You'll have to find some other way to identify it, based on something that doesn't change. You haven't given us enough information for us to help you do that, but some ways are
Where it is in the structure of the page, a compound selector could find it. For instance, if it were the first a element with href="javascript:void(0)" that's inside a div with class header, then document.querySelector("div.header a[href='javascript:void(0)']") would find it. Or if that span.thin is consistent, then document.querySelector("a > span.thing").parentNode.
If there's something about the id that doesn't change, an attribute substring selector could work (document.querySelector("a[href*='substring']")).
If it's always the 4th (or whatever) a element with href="javascript:void(0)", you could find it based on that (document.querySelectorAll("a[href*='javascript:void(0)']")[3]).
...etc. The tools are:
document.getElementById - But you'd have to know its id, so that's out.
document.querySelector - Find the first element that matches the given CSS selector. Can be a full selector, including a compound one. Any valid CSS selector works.
document.querySelectorAll - Finds all elements that match the given CSS selector (as a list).
I have a element with a child of an empty paragraph. That looks like this. Photo for easier viewing.
<body contenteditable="true" class="cke_editable cke_editable_themed cke_contents_ltr cke_show_borders" spellcheck="true">
<p><br></p>
</body>
How do I edit the area between the two p's using javascript to what ever I want since there is no id on them.
var onlineContent = document.getElementsByClassName("cke_editable cke_editable_themed cke_contents_ltr cke_show_borders");
All I have so far is this.
If you are using Jquery you can try this :
$(".cke_editable p:first").html("The text has changed");
You can also read more about how jQuery :first Selector works here: http://www.w3schools.com/jquery/sel_first.asp
document.getElementsByClassName returns an array-like object so you need to select with:
var onlineContent = document.getElementsByClassName("cke_editable cke_editable_themed cke_contents_ltr cke_show_borders")[0];
var onlineContentInner = onlineContentOuter.getElementsByTagName("p")[0];
the 0-th (meaning first) element.
An alternative method is given with document.querySelector(A_VALID_CSS_SELECTOR) wich return only the first element found (equals document.querySelectorAll(CSS_SELECTOR)[0]).
A valid css selector would be .cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders
and your element would be (using document.querySelector):
var onlineContentInner = document.querySelector(".cke_editable p");
There you have it.
It would be like this.
var onlineContent = document.getElementsByTagName("body")[0];
onlineContent.getElementsByTagName("p")[0].innerHTML = "Content between the p tags";
Reference http://www.w3schools.com/jsref/met_element_getelementsbytagname.asp
First of all, sorry If it isn't clear in the beginning, but let me explain: I want to get the div with a class and the first <ul> from a document (I'm using blogger). I already have a JS that picks up the first image and creates a thumbnail like this:
//<![CDATA[
function bp_thumbnail_resize(image_url,post_title)
{
var show_default_thumbnail=true;
if(show_default_thumbnail == true && image_url == "") image_url= default_thumbnail;
image_tag='<img src="'+image_url.replace('/s72-c/','/')+'" class="postimg" alt="'+post_title+'"/>';
if(image_url!="") return image_tag; else return "";
}
//]]>
and below,
document.write(bp_thumbnail_resize("<data:post.thumbnailUrl/>","<data:post.title/>"));
Now the structure that I want (because I cannot display the full post in the homepage due to the size of other elements):
<div class="Title1">
<h3>Title</h3>
</div>
<ul>
<li>DESCRIPTION1</li>
<li>DESCRIPTION2</li>
</ul>
There are number of ways in which you can do that. Few are
var firstUL = document.getElementsByTagName('ul')[0];
var firstUL = document.querySelector("ul");
If you also have Jquery in use
$( "ul" ).first();
or
$("ul:first")
How to get the first element from a document in JavaScript?
You could try something as simple as:
var firstUlElement = document.getElementsByTagName('ul')[0];
The getElementsByTageName method of document
returns a live HTMLCollection of elements with the given tag name. The
subtree underneath the specified element is searched, excluding the
element itself. The returned list is live, meaning that it updates
itself with the DOM tree automatically.
as it is stated here.
var firstUl = document.querySelector('ul');