Javascript grab a group of class names and add them as IDs - javascript

Is there a way with Javascript to store all the class names inside #links into an array and use a loop to assign each an ID of that class?
Below would be before
<div id="links">
some link
some link
some link
some link
</div>
after javascript
<div id="links">
some link
some link
some link
some link
</div>

Here are two plain-vanilla ways to do it with JavaScript (no jQuery). Of course this assumes that your only have the one class per element.
var elem = document.getElementById('links');
for (var i = 0; i < elem.getElementsByTagName('a').length; i++) {
elem.getElementsByTagName('a')[i].setAttribute('id',elem.getElementsByTagName('a')[i].className)
}
or
var links = document.getElementById('links').getElementsByTagName('a');
Array.prototype.map.call(links, function (el) {
el.setAttribute('id',el.className)
});

Related

Hide Anchor tag based on href URL

I was wondering if there is a possibility to HIDE anchor tags that refer to a particular URL.
I know there is possible to hide based on id like this with JavaScript:
document.getElementById('someID').style.display = 'none';
Check
But let's say I want to hide all anchor tags based on URL example: www.example.com
Check
Check
I want to hide the first anchor tag, not the second that refers to example2.com
Is this possible with pure JavaScript and not jQuery?
You can use document.querySelector to select bu attribute value like this.I have used no jquery the only javascript is used.
document.querySelector("[href='www.example.com']").style.display = 'none';
Check
Check
Simply loop through all anchor elements and then check their href:
var anchors = document.getElementsByTagName('a');
for (var i = 0; i < anchors.length; i++) {
if (anchors[i].href == 'https://example.com/') {
anchors[i].style.display = 'none';
}
}
Check
Check
You can use javascript to do the job. Use querySelector to get all the elements with same id. Then loop the ids and compare the href link value.
<script>
var elements = document.querySelectorAll("[id='someID']");
for(var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute("href") === "www.example.com") {
elements[i].style.display='none';
}
}
</script>
Working fiddle link
You can make condition
var url = document.getElementsByTagName('a');
if (url.href = "www.example.com")
{
url.style.display = none;
}
It is not exact code. i provided you example .kindly try it and let me know. It is for single . if you have many tags then loop all those

Change only the text of an anchor javascript

I'm trying to write a simple script which will change the text of a number of anchors on a page. I'm quite new to Javascript and I'm able to change the anchors but it changes the whole tag including removing the href.
How do I edit just the text only without affecting the href?
<body>
<div class="loop-add-to-cart">
Add to basket
<div class="wpd-buttons-wrap-simple" data-id="11544">
Design from blank
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.getElementsByClassName('wpd-buttons-wrap-simple');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
</script>
</body>
You can use a query selector to get all a tags inside an element with a class of wpd-buttons-wrap-simple:
document.querySelectorAll('.wpd-buttons-wrap-simple a');
You can then set the textContent or innerHTML of the link.
<body>
<div class="loop-add-to-cart">
Add to basket
<div class="wpd-buttons-wrap-simple" data-id="11544">
Design from blank
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].textContent = "Test";
};
}
buybuttons();
</script>
</body>
Using 'querySelectorAll' you can get the element the class and the element inside as below:
document.querySelectorAll('.wpd-buttons-wrap-simple > a')
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
You are currently overwriting the innerHTML of the div element, but you are looking for the anchor element inside of the div.
Use document.querySelectorAll to get all of them, or document.querySelector to only get the first.

Different ways to click a hyper link programmatically?

What are some other ways to programmatically click a text link on a page? The link does not have a ID and will not have one.
example link will look like this:
<div unselectable="on" class="x-grid-cell-inner " style="text-align:left;">
Click Here
</div>
Here's one way I can do it but want to know more ways to click it.
var els = document.getElementsByTagName('a');
for (var i = 0, l = els.length; i < l; i++)
{
var el = els[i];
if (el.text === 'Click Here')
{
el.click()
}
}
It can't have an id? That would be the best route IMO. Second best approaches:
Assign a class, and look up by class
or
Assign an id or class to the parent object, and look up the first "a" child

Show/Hide Elements with multiple attributes by attribute selection (Javascript)

I try to find an easy solution (I am a totally coding beginner, just use javascript in widgets of a "out of the box" page) for the following problem:
There are multiple attributes visitor can select by click Remove/Show
attribute a (Remove/Show)
attribute b (Remove/Show)
attribute c (Remove/Show)
a.s.o.
based on visitors "selection", I would like to show or hide the list of elements:
element 1 (attribute a and b) - Remove if "a" OR "b" has been selected
element 2 (attribute a) - remove if "a" has been selected
element 3 (attribute a and c) - remove, if "a" OR "c" has been selected
a.s.o.
I am able already to hide elements based on a "selection", but in my solution every element show and hide only based on the unique ID (and so also only on the single selection).
The Javascript I found for that is:
<script type="text/javascript">
//<![CDATA[
function swap(openlink,closelink, linkid, dataid)
{
if( document.getElementById(dataid).style.display == 'none')
{
document.getElementById(dataid).style.display='inline';
document.getElementById(linkid).firstChild.nodeValue=closelink;
} else
{
document.getElementById(dataid).style.display='none';
document.getElementById(linkid).firstChild.nodeValue=openlink;
}
}
//]]>
</script>
And than I could use this HTML Code to Remove/Show the elements:
attribute a Remove
attribute b Remove
attribute c Remove
And my element will be Remove/Show by this:
<div id="showmeA" style="display:inline">Element 1</div>
<div id="showmeB" style="display:inline">Element 2</div>
<div id="showmeB" style="display:inline">Element 3</div>
Is there an easy way to add 2 ids to one "element", so that for example Element 1 could be hidden by id=showmeA AND id=showmeB?
You said the issue yourself: IDs are unique.
This is exactly why you should use something else than id, and class attribute is perfectly fine as it does not have to be unique.
Then, this means that the function will not look for your elements using getElementById() but getElementsByClassName().
Note that this function get elements, this involves that you have to loop through these elements and hide / show the ones targeted.
function swap(openlink, closelink, linkid, dataclass) {
var elements = document.getElementsByClassName(dataclass);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if(element.style.display == 'none') {
element.style.display='inline';
document.getElementById(linkid).firstChild.nodeValue=closelink;
} else {
element.style.display='none';
document.getElementById(linkid).firstChild.nodeValue=openlink;
}
}
}
Do not forget to replace id by class attributes to your HTML, you can put in as much as you want, they simply must be separated by a space:
<div class="showmeA showmeB">Element 1</div>
<div class="showmeB">Element 2</div>
<div class="showmeC">Element 3</div>
Here is an example that you can use to better understand the function and attributes used in your solution, this solves your issue: https://jsfiddle.net/sy2mxscf/
It is also important to inform you that inline Javascript is bad, you should reconsider your code when your Javascript skill will increase.
In order to solve the issue pointed out in the comments, you have to use some kind of counter and increment it when you hide the element, decrement it when you show element of one of his class, and displaying the associate element when this counter is 0.
This is also why you need two differentiated links: the "Remove" to increment, and the "Show" to decrement.
There are several way to implement this solution:
Use an associative array in Javascript
Use a custom attribute on the element
Add and remove specific classes
I chose the last one but this may be not the best one, this is just one of the possibilities.
https://jsfiddle.net/sy2mxscf/2/
The idea is to add or remove a custom "hidemeX" class. If you click on two different "Remove" links targeting the same element, two classes will be added. If you then click on any "Show" link, the associate class will be removed. But there is still a "hidemeX" class remaining until you click on the second link, so the element is not displayed thanks to CSS.
As Delgan says, its better to use class here, and you can use those <a>'s id as their class, so when you use your function swap, you can easily trace back to decide if the elements is selected, so the div should be removed.
Below is how you can separate javascript logic and html structure.
var swap = function(e) {
var close = 'Remove', open = 'Show';
var next = this.text === close ? open : close;
// Set the clicked <a>'s text.
this.text = next;
// Get divs that will affect by this <a>
var affectTarget = this.id;
// Affected div elements
var targets = document.getElementsByClassName(affectTarget);
var i, len = targets.length;
var visible;
var watch, wLen, j;
// For each <div> that will be affect by the clicked <a>, we have to chec :
for (i = 0; i < len; ++i) {
// Get the classes that used as a list to show which <a> will have a effect on it.
watch = targets[i].classList;
wLen = watch.length;
// visibilty is default to inline, if no <a> that it watches is selected, then it'll show
visible = "inline";
for (j = 0; j < wLen; ++j) {
// If any of the <a> it watches is selected, set the visibilty to none.
if (document.getElementById(watch[j]).text === open) {
visible = "none";
break;
}
}
targets[i].style.display = visible;
}
};
// For each switcher, we register a click event for it.
var switchers = document.querySelectorAll("a.showSwitcher");
var i, len = switchers.length;
for (i = 0; i < len; ++i) {
switchers[i].addEventListener('click', swap);
}
attribute a Remove
attribute b Remove
attribute c Remove
<hr/>
<div class="swaplinkA swaplinkB" style="display:inline">Element 1</div>
<div class="swaplinkA"style="display:inline">Element 2</div>
<div class="swaplinkA swaplinkC"style="display:inline">Element 3</div>

target selected members of an array

I have a series of divs of the same class; some with title attributes set - some without:
<div class="component_wrapper cw1" title="thisTitle1">... </div>
<div class="component_wrapper cw2" title="thisTitle2">... </div>
<div class="component_wrapper cw3" title="thisTitle3">... </div>
<div class="component_wrapper cw4" title="">... </div>
<div class="component_wrapper cw5" title="">... </div>
I've constructed a javascript function that loops through these divs and displays the ones with the title attribute set by setting their css display attribute to "inline":
function checkComponent(e){
var hdrSet = document.getElementsByClassName("component_wrapper");
var titles = {};
for (var i=0; i<hdrSet.length; i++){
if ( !titles[ hdrSet[i].title ] ) {
titles[ hdrSet[i].title ] = true;
hdrSet[i].style.display = "inline";
}
}
}
checkComponent();
the problem is, when I load the page the divs that I'm trying to target display (good), but also 1 of the divs not targeted displays. In the example above, the first four divs display, when all I want is the first three. What's wrong with my code... and is there an better way to construct the function?
Your code checks for duplicate titles, not missing ones. Here's how you could fix that:
function checkComponent(){
var hdrSet = document.getElementsByClassName("component_wrapper");
for (var i = 0; i < hdrSet.length; i++){
if(hdrSet[i].title) {
hdrSet[i].style.display = "inline";
}
}
}
checkComponent();
Also, if you're open to using jQuery, it's much neater and more compatible:
function checkComponent() {
$('.component_wrapper[title]:not([title=""])').css('display', 'inline');
}
checkComponent();

Categories

Resources