HTML/JS referencing IDs - javascript

I'm wondering how to reference an HTML id or a class in JavaScript in the following context.
<script type="text/javascript">
(function() {
var menu = document.querySelector('ul'),
menulink = document.querySelector('**REFERENCE CLASS**');
menulink.addEventListener('click', function(e) {
menu.classList.toggle('active');
e.preventDeafult();
});
})();
</script>
I'd appreciate any help I can get, thanks.

Let's say you have an element with class attribute equals to "my-class" and you want to select that element with JavaScript. Here as an example i'll select an element based on its class attribute and change his color to green using only JavaScript.
// referencing the element with class attribute containing my-class using querySelector() method that you used it in your code, notice the " . " (dot) before the class-name
var myClassDiv = document.querySelector('.my-class');
// changing the text color to green
myClassDiv.style.color = '#0F0';
<div class="my-class">by default my color is black but JavaScript made me green !</div>
Explanation:
The method querySelector() receives a string representing a fully qualified CSS selector. i.e querySelector('body #main > ul.menu > li.class-name') and as the same selector can match many elements in the same document this method returns only the first element matched by the selector.
To get all the elements matching a selector you could use querySelectorAll() that returns an array of the matched elements.
You wanted to select an element based on it's class-name, JavaScript provides a method that fetches all the elements based on a class-name: getElementsByClassName() that returns an array containing the matched ones even if there is only one element. It rereceives a string representing a class-name, NOT as you write it in CSS i.e getElementsByClassName('class-name') NO dot before the class-name.
To do the same task as we did in the top of that answer
, I'll be using the getElementsByClassName() instead of querySelector().
// referencing the element with class attribute containing my-class
var myClassDiv = document.getElementsByClassName('my-class')[0];
// changing the text color to green
myClassDiv.style.color = '#0F0';
<div class="my-class">by default my color is black but JavaScript made me green !</div>
Hope I pushed you further.

Related

JavaScript: Select an element to a div and update styling

I need to add styling to a DIV element using JavaScript. I have the following DIV in my document:
<div class="RnEpo Yx5HN " role="presentation">
The script that I have tried is:
WebElement = document.querySelectorAll("div[class='RnEpo Yx5HN ']");
WebElement.style='height: 10000px;'
WebElement.setAttribute("height = 1000px;");
I want to achieve the same styling as this CSS:
.RnEpo Yx5HN
{
height: 100000px;
}
To achieve what you require, first replace querySelectorAll() with querySelector() seeing that your only need to select the first matching element.
Consider also revising your selector from div[class='RnEpo Yx5HN '] to a more robust selector in the form of div.RnEpo.Yx5HN which is to say:
Select div elements that have classes any ordering of class RnEpo and Yx5HN
Lastly, revise the way that you're applying the inline style so that the height attribute is directly specified on the WebElement style object.
These changes make the call to setAttribute() redundant. Note also that; setAttribute() takes two arguments, and the DIV element does not have a native height attribute.
Here's a working snippet showing this in action:
/* Use querySelector() to select first matching element and use dot notation syntax to select div with both classes */
const WebElement = document.querySelector("div.RnEpo.Yx5HN");
/* Apply inline style, avoid invalid setAttribute call */
WebElement.style.height = `10000px;'
<div class="RnEpo Yx5HN" role="presentation">

JavaScript: Add a class specific tag in classList

I have a class named X which has multiple <span> inside and I also have a css selector X span.
In JavaScript how can I use X span instead of X in the following case:
document.querySelector('.ABC').classList.add(X)
I tried document.querySelector('.ABC').classList.add(X span) which definitely isn't working.
In Javascript, working with the HTML works like this:
You ask the browser to give you an object or list of objects that correspond to the HTML elements
You use the objects to modify the page
If I understand correctly, what you want to do is:
Find element by className ".ABC"
Find "span"-s inside that element
Give those spans a class
To do those, follow these steps:
// get the first element that matches .ABC
let parent = document.querySelector(".ABC");
// now parent is either an Element, or undefined/null
// if it's not null, we can call querySelectorAll
// get all elements inside the parent that are spans
let spans = parent.querySelectorAll("span");
// spans is now either an array of Elements, or undefined/null
// if it's not null, we can iterate over it
for (let span of spans) {
span.classList.add('X');
}

How to change a style property of element by class name without any use of ID's in JS?

I am doing a school project and it's my first time using JS, and we are not allowed to use any ID's for css styling, but on some event that the user does I want to change the style of a div in the page:
HTML:
<div class="ads">
...
</div>
CSS:
.ads{
display:block;
//and some other style properties
}
and when the user do the event I want to change the display property into :
display : none;
I know how it can be done using ID for the element, but how can it be done only by a class name?
I would like to be able to do it something like this:
document.getElementsByClassName('ads').style.display=none;
Thank you.
If you know that there is only one element with that class, use the first element of the NodeList that document.getElementsByClassName returns:
document.getElementsByClassName('ads')[0].style.display = 'none';
document.getElementsByClassName('ads')[0].style.display ='none';
If you have just a one element with class"ads", you can use:
document.querySelector('.ads').style.display='none'
Else, if you have more than one element you can add a unique class name for you element like this
<div class="ads foo">
and using document.querySelector('.foo').style.display='none'
for changing it's style.
You should put index, also the string after the equal sign must be with quotation marks, like below:
document.getElementsByClassName('ads')[0].style.display="none";
w3schools
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Javascript or JQuery string get substring with certain prefix

I have an element with many classes, I would like to access a specific class to get the last digit of it (I realize a data-attribute or ID may have been better options but for now I am stuck with class). I already am able to select the element using it's ID so I only need to identify what the last digit of the my-target-* is.
Example
<div class="foo bar apple my-target-1"></div>
I would like to get the class my-target-* and then extract the 1 from it.
Loop over all the elements containing 'my-target', assuming it is the last class, split the classes by space, get the last class, split it by '-' then get the needed value to extract.
Here is a working example:
$(document).ready(function(){
$("[class*= my-target]").each(function(){
var extract= $(this).attr('class').split(' ').pop().split('-').pop();
$("#result").html(extract);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo bar apple my-target-1"></div>
<span id="result"></span>
Here's a jQuery selector that should target your element:
$("[class*=my-target]");
But this may be more general than you need: this uses the CSS substring selector *=, so this would also match elements like the following:
<div class="not-my-target"></div>
You can try a combination of selectors to get something more specific:
$("[class^=my-target], [class*= my-target"]);
This combines the CSS starts with selector, with the contains.
Now to grab the data that you want from the class name you'll need to do some string parsing on the class attribute:
var numberToExtract = -1;
var elem = $("[class*=my-target-]");
if (elem)
{
classes = elem.attr("class").split(/\s+/);
$.each(classes, function(idx, el)
{
if (el.startsWith("my-target-"))
{
numberToExtract = el.split("-").pop();
return false;
}
});
}
Maybe is neater if you use a data element to do this
<div class="foo bar apple my-target-1" data-target="1"></div>
And you get this by doing:
$('.my-target-1').data('target')
It's better than parsing the class
To get any one starting with those classes try this
$('div[id^=foo bar apple my-target]')
If you're stuck using a class instead of a data attribute, you can extract the full string of classes from the object you've found with:
obj.attr('class')
and then match that against a regular expression that uses word boundaries and capturing parentheses to extract the number at the end of 'my-target-*'
You must have ID to catch the particular div or span content.
Be Careful , Perhaps , you have a class and a subclass .
<div id='id' class='myclass mysubclass' >Testing</div>
So if you want to have the class selector, do the following :
var className = '.'+$('#id').attr('class').split(' ').join('.')
and you will have
.myclass.mysubclass
Now if you want to select all elements that have the same class such as div above :
var class=$('.'+$('#id').attr('class').split(' ').join('.'))
that means
var class=$('.myclass.mysubclass')
If you want second class into multiple classes using into a element
var class_name = $('#id').attr('class').split(' ')[1];`
or You can simply use var className = $('#id').attr('class'); this will return full name class and subclass then handle it using JQuery/JavaScript substring method.

Write text Attribute inside of div tag

I need to know how i can add some javascript to add value inside text like below
The original div in HTML code like
<div> Text </div>
I need the some way to put an value inside the div appear in source like below
<div data-texe> Text </div>
I have try but its new for me
<script>
var div = document.getElementByDIV;
div.innerDIV += 'data-texe';
</script>
You want to set attribute?
var div = document.getElementById('yourid');
div.setAttribute('data','texe')
You will need to first find a way to identify your <div> elements, either with a unique ID or a class name. In this example I chose a unique ID:
<div id="test">Text</div>
If you want to add your data-texe attribute to all <div>s, you could use document.getElementsByTagName() and then loop over the results.
But let's stick to altering just one element for this example:
<script type="text/javascript">
// getElementByDIV is obviously not a valid function, so let's use
// one that finds an element by its ID:
var div = document.getElementById('test');
// The setAttribute function lets you add an attribute to the element
// The first parameter is the attribute name and the second is its value
// Attributes with no values are implicitly defined as empty string
div.setAttribute('data-texe', '');
</script>

Categories