I have the following fiddle.
When you click the Hide button the numbers 2, 3 and 1 are hidden. All works great using this Jquery code:
$( "#hide" ).click(function() {
$('span').each(function(){
if($(this).text().match(/^([1-9])$/))$(this).hide()
});
});
Now I want the same thing, but with using a good old javascript function instead of the jQuery solution given above. How to do this? See my (not working) attempt here.
Many thanks
Here is a simple vanilla JS version:
function hide() {
var spans = document.getElementsByTagName('span'), i = 0;
for(i=0; i<spans.length; i++) {
spans[i].style.display = (spans[i].innerText.match(/^[1-9]+$/) ? 'none' : '');
}
}
Note: I've corrected your regex to match numbers with more than 1 digit in it.
Updated fiddle: http://jsfiddle.net/WnLUu/6/
In plain javascript you could access the style attribute, so instead of $(this).hide() you could call
this.style.visibility = "hidden"
Maybe something like this.
function buttonClicked(evt) {
var spans = document.getElementsByTagName("span");
for (var i = 0, length = spans.length; i < length; ++i) {
if (/^([1-9])$/.test(spans[i].innerHTML)) {
spans[i].style.display = "none";
}
}
};
document.getElementById("hide").addEventListener("click", buttonClicked, false);
Please try this (works on IE and other browsers, .innerText is IE specific):
function hide() {
var spans = document.getElementsByTagName('SPAN');
for (var i=0; i < spans.length; i++) {
alert(spans[i].textContent);
if (spans[i].textContent !== undefined && spans[i].textContent.match(/^[1-9]$/))
spans[i].style.display = 'none';
else if (spans[i].innerText !== undefined && spans[i].innerText.match(/^[1-9]$/)) // IE
spans[i].style.display = 'none';
}
}
Related
I am using the below code in the google tag manager custom JavaScript variable, but it returns same index value for every line item, what can be the issue?
Web page link: https://www.amity.edu/programe-list.aspx?fd=all
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[i].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
There is an error in the 5th line.
It should be elements[index].children... in that case.
The updated code:
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[index].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
Here is an alternative way from Simo's blog
Blog link
Although the post is say about visibility element. I test it with click on my website.
This might work
function() {
var list = document.querySelectorAll('.staff-container a'),
el = {{Click Element}};
return [].indexOf.call(list, el) + 1;
}
If it is not working, you might need to provide the screenshot about the click element from your GTM preview.
This is my code please covert my jQuery into javascript.
Convert in javascript
$(".wrapper td li>span").text(function () {
return $(this).text().replace(".", "");
});
Using querySelectorAll and textContent
document.querySelectorAll('span').forEach(function(el) {
el.textContent = el.textContent.replace(/\./g, '')
});
<span>1. abc</span><br/>
<span>2. def</span>
Finally I got a proper answer to convert jQuery to JavaScript with and issues on enterprise mode of internet explorer
var spans=document.body.querySelectorAll('.wrapper td li>span')
for (i = 0; i < spans.length; i++) {
spans[i].innerText = spans[i].innerText.replace(/\./g, '')
}
I´m trying to add target=“_blank” to all the links within the divs with an specific class name. I know how to do it with an ID:
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
But i´m trying to replicate the same, using classes instead of IDS. Any ideas of a how to do this without jquery?.
Thanks in davanced!
You can use querySelectorAll() and include a CSS selector. So if your class name is link-other:
document.querySelectorAll('.link-other a')
.forEach(function(elem) {
elem.setAttribute('target', '_blank');
})
<div class="link-other">
Wikipedia
Google
</div>
Use querySelectorAll and loop just like you did.
var anchors = document.querySelectorAll(".link_other a");
Or you can use getElementsByClassName and nested loops.
var parents = document.getElementsByClassName(".link_other");
for (var i = 0; i < parents.length; i++) {
var anchors = parents[i].getElementsByTagName("a");
for (var j = 0; j < anchors.length; j++) {
anchors[j].setAttribute('target', '_blank');
}
}
You can use document.querySelectorAll() which takes a css expression:
var anchors = document.querySelectorAll('.my_class a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
Or (ab)using the array prototype:
[].forEach.call(document.querySelectorAll('.my_class a'), function(el) {
el.setAttribute('target', '_blank');
});
You should also consider using addEventListener instead of window.onload:
window.addEventListener('load', function() {
// ...
});
Or the more appropriate:
document.addEventListener('DOMContentLoaded', function() {
// ...
});
You can also use the old school <base> element which will can set defaults for all a tags:
var base_el = document.createElement('base');
base_el.setAttribute('target', '_blank');
document.head.appendChild(base_el);
To achieve your expected result use below option
var addList = document.querySelectorAll('.link_other a');
for(var i in addList){
addList[i].setAttribute('target', '_blank');
}
Codepen - http://codepen.io/nagasai/pen/QEEvPR
Hope it works
Is there a way to deselect or unclick a button that has been clicked using javascript?
So basically I have a button:
if (i === 10) {
var clicked = document.getElementById('i10');
clickedButton.push(click.textContent);
clicked.style.color = "pink";
}
So when i click that button it turns the text to pink. Is there a way to click on the button again and have it remove the push and turn the text back to black?
Sorry, Javascript isn't my strongest point.
Web programming lesson time: if you want to set styles, don't use JavaScript to set the style, use CSS for the styling definitions, and then only use JavaScript to point to that CSS.
In your CSS:
.highlight {
color: pink;
background: blue;
font-style: fantasy;
whatever-else: StuffGoesHere;
}
And then your button handling:
button.addEventListener("click", function(evt) {
var e = find.your.element.however.you.need();
e.classList.toggle("highlight");
});
Magic: simply by doing things the right way, the code is extremely straight forward, AND we're not hardcoding the styling, we're simply referring to where styling should be defined.
"But what if the browser doesn't support .classList?": the only reason to say this is because you did not keep up with how much browser have improved. Every browser supports classList.
Of course, if you need to do more than just toggles, write your function as a standalone operation, and throw elements at it:
var records = {};
function toggleHighlight(e) {
e.classList.toggle("highlight");
if (e.classList.contains("highlight")) {
// element is now highlighted, do things accordingly:
records[e.id] = e.textContent;
// ...
} else {
records[e.id] = false;
// ...
}
}
button.addEventListener("click", function(evt) {
var e = find.your.element.however.you.need();
toggleHighlight(e);
});
Do this help you?
function onclick(){
var clicked = document.getElementById('i10');
if(clicked.style.color == "pink"){
clicked.style.color == "black";
}
else{
clicked.style.color == "pink";
//do your businesses
}
}
From the shared code, you can do something like check if the textContent already exists in teh array if so it is already clicked so remove it from the array and change the color
if (i === 10) {
var clicked = document.getElementById('i10'),
index = clickedButton.indexOf(click.textContent);
if (index > -1) {
clickedButton.push(click.textContent);
clicked.style.color = "pink";
} else {
clickedButton.splice(index, 1);
clicked.style.color = "";
}
}
Yes:
if (i === 10) {
var clicked = document.getElementById('i10');
var index = clickedButton.indexOf(click.textContent);
if (index === -1) {
// toggle on
clickedButton.push(click.textContent);
clicked.style.color = "pink";
} else {
// toggle off
clickedButton.splice(index, 1);
clicked.style.color = "";
}
}
This will check if click.textContent is already in the clickedButton array. If it is it will remove it from that array as well as reset button color to whatever default is.
Please note that, searching arrays using indexOf is not supported in IE7-8. If you need support for those browsers, you will need to implement this as well:
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, i /*opt*/) {
if (i===undefined) i= 0;
if (i<0) i+= this.length;
if (i<0) i= 0;
for (var n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
The above is taken from StackOverflow thread: Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.).
I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS