How can I Disable an element when URL contains a specific string? - javascript

<div class="test-class">
<div class="test-class1" id="test-id1">hello 1</div>
<div class="test-class2" id="test-id2">hello 2</div>
<div class="test-class3" id="test-id3">hello 3</div>
</div>
And I would like to Disable/hide the Second [div] (id="test-id2") , when the page URL contains the string ?fullpost.
So for example: if my URL is http://www.example.com/post_1.html?fullpost then test-id2 div should not be active.
And if the URL is for example only http://www.example.com/post_1.html then test-id2 div should be active.
<script>
let element = document.getElementById("test-id2");
if(window.location.href.search("?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>
My script is not working.

Try this instead
<script>
let element = document.getElementById("test-id2");
if(window.location.href.includes("?fullpost")){
element.parentNode.removeChild(element);
}
</script>

It looks like when I run it window.location.href.search("?fullpost") naturally gets parsed as a regular expression. So you need to escape the '?'
<script>
let element = document.getElementById("test-id2");
if(window.location.href.search("/?fullpost") > -1){
element.parentNode.removeChild(element);
}
</script>
Another way to do it would be to use includes()
if(window.location.href.includes("?fullpost"))
{

I fixed it using Regex check the next code
var element = document.getElementById("test-id2");
var reg = /(\?|\&)?fullpost/g;
var url = window.location.href;
if (reg.exec(url) !== null) {
element.parentNode.removeChild(element);
}
Here's the full page of the snapshot https://output.jsbin.com/cataxix?fullpost
The regex will check if the URL contains fullpost as the first parameter or wherever it is in the URL as a parameter.
If your URL was like that http://www.example.com/post_1.html?anything&fullpost it will work.

you should use indexOf() instead of search ()
let element = document.getElementById("test-id2");
var url = window.location.href;
if(url.indexOf("?fullpost") > -1)
{
element.parentNode.removeChild(element);
}

add a listener on that element -- you want it to prevent only for a specific page
let ELM = document.getElementById("test-id2");
ELM.addEventListener("click",(ev) => {
if(window.location.href.test(/\?fulpost/)){
//ev.preventDefault(); // for <a></a>
ev.stopImmediatePropagation(); // this will prevent any click_event from execution
}
},true);

Related

Hide div if URL hash begins with word in Javascript

How could I hide divs that begin with id "news" but also contain a number like "news1" "news2" etc if the URL hash doesnt contain "news".
like hide if someurl.com/#events. but show any "news" div if someurl.com/news1
need in regular JS
thanks,
Try This:-
$(function(){
var url = window.location.hash;
if(url.indexOf('news') > -1){
$("div[id^='news']").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="news1">News1</div><br>
<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>
Update: (Using Pure JavaScript)
(function() {
var url = window.location.hash;
/* for testing set the hash to 'news' */
url='news';
if(url.indexOf('news') > -1){
var bodyDOM = document.body;
bodyDOM.querySelectorAll("[id^='news']").forEach(function(item, index){
item.style.display='none';
});
}
})();
<div id="news1">News1</div><br>
<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>
The script hasn't been tested. It does these steps:
Looking for the word "#news" in URL. In our case, if there aren't any word.
For each div with the ID "new" or similar
Add a CSS to this div to hide it.
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("#news") < 0) {
$("div[id^='news']").css('display', 'none');
}
});
</script>
If you put a class on all the divs you'd want this apply to, you can do this:
$(document).ready(function() {
$('.CLASSNAME').each(function(i) {
if($(this).val().indexOf('WORD_YOURE_LOOKING_FOR') > -1) {
$(this).css('display', 'none');
}
);
});
Well you can access the hash in a URL like so:
var hash = window.location.hash;
I'm not 100% clear what you want to do at that point. If you wanted to show the news1 div, you'd do this:
if(hash == 'news1') {
$('#news1').show();
}
Try this:
var hash = window.location.hash;
$('[id^="'+hash+'"').hide();

Replace All URLs within DIV

I would like to amend all URLs within a specified DIV but unsure how to. An example I want is:
<div id="SearchList">
up
down
left
right
</div>
So for example I would like to amend the URLs to be displayed as follows:
<div id="SearchList">
up
down
left
right
</div>
Any ideas how this can be achieved?
// For each anchor element...
$("#SearchList a").each(function() {
// Change its 'href' attribute to...
$(this).attr("href",
// Its current 'href' attribute with a .replace() called
$(this).attr("href").replace("google", "bing"));
});
This is what I would do
$('#SearchList a').each(function(){
var $el = $(this),
hash = $el.attr('href'),
replace = 'www.bing.com',
regex = /www.+.com\//,
replacement = hash.replace(regex, replace);
$el.attr('href', replacement);
});
Shorter would be
$('a').prop('href', function(i,e){ return e.replace('google', 'bing')});

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

How to find element of div from another div

I have the elements in the div as mentioned below:
<div id="container">
<div id="first_div">
<div id="comment-1" class="comment">Child 1 of first div</div>
<div id="comment-2" class="comment">Child 2 of first div</div>
<div id="comment-3" class="comment">Child 3 of first div</div>
<div id="comment-4" class="comment">Child 4 of first div</div>
</div>
<div id="second_div">
<div id="comment-5" class="comment">Child 1 of second div</div>
<div id="comment-6" class="comment">Child 2 of second div</div>
<div id="comment-7" class="comment">Child 3 of second div</div>
<div id="comment-8" class="comment">Child 4 of second div</div>
</div>
<div id="third_div">
<div id="comment-9" class="comment">Child 1 of third div</div>
<div id="comment-10" class="comment">Child 2 of third div</div>
<div id="comment-11" class="comment">Child 3 of third div</div>
<div id="comment-12" class="comment">Child 4 of third div</div>
</div>
I need to retrieve the next element from comment id comment-4.
$('#comment-4').next().attr('id') gives me result as undefined.I need the target div to be comment id - comment-5.How to retrieve the next element of div from another div using jquery?
Try this :
$(function(){
$('.comment').click(function(index){
var id;
if ( $(this).is(':last-child') )
id = $(this).parent().next().children(':first').attr('id');
else
id = $(this).next().attr('id');
alert(id);
});
});
Demo
Demo : http://jsfiddle.net/abdennour/PU54r/
function nextOf(id,cyclic){
var ids= $('div[id^=comment-]').toArray().map(function(e){return $(e).attr('id')}).sort();
var idx=ids.indexOf("comment-"+id);
if(idx!==-1){
if(ids.length> idx+1){
return $('div#'+ids[idx]);
}
else{
// it is the last div: if it is cyclic ,you may return the first
if(cyclic){
return $('div#'+ids[0]);
}
}
}else{
// no div with this id
}
}
Then :
var target=nextOf(4)
if(target){
target.html()
//--> Child 1 of second div
}
I think you can use $('.comment') to pick up all of your wanted, and save them in some variable such as var arrResult = $('.comment');.
So far, you can choose what you wanted use the arrResult variable.
Because your inner-most divs have different parents, I would first get all the divs you care about:
var comments = $('.comment');
Next, if we can assume your id's are all numbered sequentially, get the number in the id (assuming this references the element):
var index = parseInt($(this).attr('id').substr(8));
Now, the next div in the comment list is at that position in the comments:
var nextDiv = comments[index];
Just for good measure, I'd first make sure index is set:
var nextDiv;
if (index < comments.length) {
nextDiv = comments[index];
}
You could use an index in your case :
JS:
for (var index = 0; index <= 12; ++index) {
$("#comment-" + index).attr("id");
}
You can define a statement which checks the target id is the last child, than you can return a function according to value.
jsFiddle Demo
var target = 'comment-4';
$('.comment').each(function(i) {
if ( $(this).attr('id') == target ) {
if ( $(this).is(':last-child') ) {
$(this).parent().next().children().first().addClass('red');
}else{
$(this).next().addClass('red');
}
}
});
Here is one way - http://jsfiddle.net/jayblanchard/WLeSr/
$('a').click(function() {
var highlight = $('.highlight');
var currentIndex = $('.comment').index(highlight); // get the index of the currently highlighted item
$('.comment').removeClass('highlight');
var nextIndex = currentIndex + 1;
$('.comment').eq(nextIndex).addClass('highlight');
});
It is showing undefined because comment-4 and comment-5 are childrens of different parent elements. Means comment-4 is children of first_div and second_div parent of comment-5.
You can get the comment-5 using below code.
$('#comment-4').parent().next().children().attr('id');
Assuming jQuery-wrapped element is collected in $comment, there's one way to solve it:
function getNextComment($comment) {
var $nextComment = $comment.next();
if ($nextComment.length) {
return $nextComment;
}
var $nextParent = $comment.parent().next();
if ($nextParent.length) {
return $nextParent.children().first();
}
return null;
}
Demo. Click on one comment - and see the next one's highlighted. )
The base algorithm's very simple here. First, we attempt to retrieve the next sibling of the given element. If there's one, it's returned immediately. If not (and it's the case with #comment-4 in your question - it's the last element in its hierarchy), we go up the DOM chain for its parent (#first-div, in this case), and look for its next sibling (#second-div). If it exists, then its very first child element is returned. If it doesn't, null is returned (we can actually return an empty jQuery object - $(), but that depends on use cases.
Just one instruction : )
$('<div id="mock" />').append($('.comment').clone()).find('#comment-4').next().attr('id')//---> comment-5
Based on divs have the same Css class .comment
DEMO
Why not this will be undefined: $('#comment-4').next().attr('id') because there is no next element. as you mentioned that you want to target the #comment-5 in the next div's child then you can do this:
function giveId(el) {
var sel = el.id ? '#'+el.id : '.'+el.className;
var id = $(sel).next('div').length ? $(sel).next('div').attr('id') : $(sel).parent('div').next('div').find('> div:first').attr('id');
return id || "Either no next elem exist or next elem doesnot have any id/class.";
}
$(function () {
$('div').click(function (e) {
e.stopPropagation();
alert(giveId(this));
});
});
Updated Demo in action
Try this: JSFiddle (The easiest solution!)
$(document).ready(function(){
var currDiv = $("#comment-4"); // Try with different valies: "#comment-x"
currDivId = currDiv.prop('id');
lastDivId = currDiv.parent('div').find('.comment').last().prop('id');
if(currDivId == lastDivId){
var nextComment = currDiv.parent('div').next('div').find('.comment').prop('id');
}else{
var nextComment = currDiv.parent('div').find('.comment').next().prop('id');
}
alert(nextComment);
});

get content of element after slicing his span

I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"

Categories

Resources