Hide an element when a specific string is present in the url - javascript

I want to hide a button when the string "wholesale' is present in the url. I've tried a few variations of the following code but it just won't work.
<script type="text/javascript">
$(document).ready(function () {
if (/wholesale/.test(window.location.href)) {
document.getElementsByClassName('variations_button')[0].style.display = 'none';
}
});
</script>

May be this will help.
var patt = new RegExp("wholesale");
if (patt.test(window.location.href)) {
$('.variations_button').hide();
}

you are doing wrong with the select element by class name code
it should be like this:
document.getElementsByClassName('variations_button')[0].style.display='none'
Note:
document.getElementsByClassName returns an array of elements with the same class name. So document.getElementsByClassName('variations_button')[0] will return the first element with the class name variations_button.

you have a problem with getElementByClassName, it should be getElementsByClassName and will return a HTMLCollection (Array like object) not an element. You should probably also use jQuery if that is already loaded on the page. jQuery is an array like object of HTMLElements that will give you methods that will run over the entire collection.
edit:
here is a working example, click 'Run code snippet' to see the result. I had to change the regex to match what was in the snippet, but you should get the idea.
console.log( 'is jQuery installed on the page', typeof $ !== void 0 );
$(function () {
console.log( 'href', window.location.href );
if (/stacksnippets/.test(window.location.href)) {
console.log('regex found in href');
$('.variations_button').css('background', '#3cf');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<button class="variations_button">variations button</button>

Related

Select element by tag/classname length

I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})

Find right line of code by Regex and replace text in it jQuery

I have two lines of javascript code at a Html body.
<script text="javascript">
Muse.Utils.initWidget('#widgetu94', ['#bp_infinity'], function(elem) { return new WebPro.Widget.Form(elem, {validationEvent:'submit',errorStateSensitivity:'high',fieldWrapperClass:'fld-grp',formSubmittedClass:'frm-sub-st',formErrorClass:'frm-subm-err-st',formDeliveredClass:'frm-subm-ok-st',notEmptyClass:'non-empty-st',focusClass:'focus-st',invalidClass:'fld-err-st',requiredClass:'fld-err-st',ajaxSubmit:true}); });/* #widgetu94 */
Muse.Utils.initWidget('#widgetu386', ['#bp_infinity'], function(elem) { return new WebPro.Widget.Form(elem, {validationEvent:'submit',errorStateSensitivity:'high',fieldWrapperClass:'fld-grp',formSubmittedClass:'frm-sub-st',formErrorClass:'frm-subm-err-st',formDeliveredClass:'frm-subm-ok-st',notEmptyClass:'non-empty-st',focusClass:'focus-st',invalidClass:'fld-err-st',requiredClass:'fld-err-st',ajaxSubmit:true}); });/* #widgetu386 */
</script>
I need to change text ajaxSubmit:true to ajaxSubmit:false only for the second line Muse.Utils.initWidget('#widgetu386'...
I've tried to use this code
<script>
document.body.innerHTML = document.body.innerHTML.replace('ajaxSubmit:true', 'ajaxSubmit:false');
</script>
But after that all of ajaxSubmitare gonna to false.
Maybe I need more Regural Expression?
<script>
document.body.innerHTML = document.body.innerHTML.replace(/MagicRegExp/, 'ajaxSubmit:false');
</script>
I just want find it by '#widgetu386'
Please help me. I don't know what to do.
You use the id of an element to make changes to that specific element. I have never used Muse.Utils.initWidget() personally, but I am assuming that the first paramter of the function is the element id.
<script>
document.getElementById("#widgetu386").innerHTML =
document.getElementById("#widgetu386").innerHTML.replace(
'ajaxSubmit:true',
'ajaxSubmit:false'
);
</script>

Grab the class from an element JS

I have an li tag that looks like:
<li class="active_fix generator" data-selected="1"></li>
Within my onClick event I have a console.log on $(this) and I get back
[li.active_fix generator] - among a few things in my console window.
How can I grab the class. So for example save the classname active_fix as a var but not the second class name generator.
$('active_fix').on('click', function() {
console.log($(this));
})
Thanks.
You can split the class name,
$(this).attr("class").split(" ")[0]
We are getting the class name using attr and splitting the string by a space, then we are getting the first key in the array.
Reading Material
attr
split
Try to use .attr("attributeName") to get its attribute(any),
$('.active_fix').on('click', function() {
console.log($(this).attr("class").split(" ")[0]); //Jquery
console.log(this.className.split(" ")[0]); //Pure Javascript
});
this.className will return a string "active_fix generator". Basically multiple classes to an element can be applied by adding a space as a delimiter. So you can split that returned string with space to get array of class names. And from that array [0] will get you the first class.
You can use classList to retrieve a list of the elemnent classes:
$('.active_fix').on('click', function() {
alert(this.classList[0]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="active_fix generator" data-selected="1">...</li>
$('.active_fix').on('click', function() {
alert($(this).attr("class").split(" ")[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="active_fix generator" data-selected="1"></li>
DevJunior Try This , It will help you
$('.active_fix').on('click', function() {
console.log($('.active_fix').attr('class').split(' ')[0]);
});
$('.active_fix').on('click', function() {
alert(this.classList[0]);
})

JQuery, a new Selection using the results

Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?

Count divs with a certain class

Seems pretty simple but I can't get it to work.
I have two divs with the class 'user'. I want to output "you have 2 divs".
<script type="text/javascript">
$(document).ready(function() {
function divcount() {
var mycount = $('.user').length();
document.write(mycount)
}
});
</script>
I'm sure I'm missing something simple..
It’s either $('.user').length (length property of Array) or $('.user').size() (size method of jQuery).
Length is a property not a function. Size is a function.
$(".user").length // use the length property
$(".user").size() // use the size method
notice that the code must be include in the $(function(){...}) block; like:
$(function(){
alert( $(".user").length );
alert( $(".user").size() );
});
It's just $('.user').length. It's a property, not a method call.

Categories