Just to give an Idea what i'm trying to do here's an example code:
$(function(){
if ($('.maybe > div > a.link:contains(".JPG, .jpg, .gif, .GIF")').length) {
alert('hello');
});
I want to check if the content of some links are containing the dot and the letters of all image extensions, like
<div class="maybe">
<div>
<a class="link" href="someURL">thisIsAnImage.jpg</a>
<a class="link" href="someURL">thisIs**NOT**AnImage.pdf</a>
</div>
</div>
<div class="maybe">
<div>
<a class="link" href="someURL">thisIs**NOT**AnImage.zip</a>
<a class="link" href="someURL">thisIsAnotherImage.png</a>
</div>
</div>
The div's and links are generated dynamically by php, so there's no way to know how many links and div's there will be once the page is generated.
How to write the code in a properply way?
Thanks a lot for helping me to resolve the problem.
Here's my first instinct:
$('.maybe .link').each(function () {
if ($(this).text().toLowerCase().match(/\.(jpg|png|gif)/g)) {
console.log("yay I did it");
}
});
Use toLowerCase() on the link text so you don't have to check both lower and upper case. Then use String.match(regex) with a regex group to match all the file extensions.
Hope this helps!
Edit: here's an example in jsfiddle. Open your javascript console to see the output of the console.log statement. http://jsfiddle.net/9Q5yu/1/
I'd suggest:
// selects all the 'a' elements, filters that collection:
var imgLinks = $('a').filter(function(){
// keeps *only* those element with an href that ends in one of the
// file-types (this is naive, however, see notes):
return ['png','gif','jpg'].indexOf(this.href.split('.').pop()) > -1;
});
// I have no idea what you were doing, trying to do, wanting to do or why,
// but please don't use 'alert()', it's a horrible UI:
if (imgLinks.length) {
console.log('hello');
}
The above is a relatively simple, and naive, check; in that it simply splits the href on the . characters and then tests the last element from the array (returned by split()) is equal to one of the elements of the array. This will fail for any image that has a query string, for example, such as http://example.com/image2.png?postValue=1234
Given the clarification in the comments, I'd amend the above to:
var fileTypes = ['png','gif','jpg','gif'],
imgLinks = $('a').filter(function(){
return (new RegExp(fileTypes.join('|') + '$', 'gi')).test($(this).text());
});
References:
JavaScript:
Array.prototype.indexOf().)
[RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
String.prototype.split().
jQuery:
filter()
Related
In the past I used Google Developer Console to delete some specific divs on a page. I could do it manually of course but in some cases where the divs where many I had to use the console. I had a single line code that did the job (I found it while searching the internet) but I lost my note.
So how can I delete using javascript any html code (by copy pasting the code).
Something like:
elements = $('<div ... </div>');
elements.remove();
OR
$('<div ... </div>').remove();
Any ideas? I am not an expert in javascript (obviously) and I've been searching stackoverflow for hours without finding anything that works.
UPDATE: I think some people might get confused with my question. Google developer console accepts javascript command lines. So even though I ask for javascript I will use the code on the google developer console.
UPDATE 2 :
Here is an example of a div I need to delete. Keep in mind I want to copy paste the entire code in the javascript code. Not just identify the div.
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
It's the data-entry-status="declined" that makes that div unique so I can't just identify the div using an id selector or a class selector. I need to put the entrire thing there and remove it.
I tried:
$('<div class="entry-status-overlay" data-entry-status="declined"><div class="entry-status-overlay__inner"><span class="entry-status-overlay__title">Declined</span></div></div>').remove();
It didn't remove the div.
Try to search the dom by its outerHTML.
function deleteDomByHtml(html){
html=html.replace(/\s/g,'');
$("*").each(function(){
if(this.outerHTML.replace(/\s/g,'')===html){
$(this).remove();
}
});
}
And try this line on this page:
deleteDomByHtml(`<span class="-img _glyph">Stack Overflow</span>`);
You cannot do by simply pasting the code. That will remove all the div element.
You may need a specific selector like id,class or child to specific parent to remove the element from the dom.
Consider this case the divs have common class but the data-entry-status is different. So you can get the dom using a selector and then check the dataset property.
For demo I have put it inside setTimeout to show the difference. In application you can avoid it
setTimeout(function() {
document.querySelectorAll('.entry-status-overlay').forEach(function(item) {
let getStatus = item.dataset.entryStatus;
if (getStatus === 'declined') {
item.remove()
}
})
}, 2000)
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div class="entry-status-overlay" data-entry-status="accepted">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">accepted</span>
</div>
</div>
Just add any attribute with [] and it will remove the element.
$('[class="entry-status-overlay"]').remove();
/*OR*/
$('[data-entry-status="declined"]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
function del(){
var h = document.body.outerHTML;
h = h.match('<div>...</div>');
h.length--;
return h;
}
I guess this will work just give it a try... i tried on browser console and it worked, this way you can match the exact you want.
I might as well add my take on this. Try running this in your console and see the question vanish.
// convert the whole page into string
let thePage = document.body.innerHTML,
string = [].map.call( thePage, function(node){
return node.textContent || node.innerText || "";
}).join("");
// I get some string. in this scenario the Question or you can set one yourself
let replacableCode = document.getElementsByClassName('post-layout')[0].innerHTML,
string2 = [].map.call( replacableCode, function(node){
return node.textContent || node.innerText || "";
}).join("");
// replace whole page with the removed innerHTML string with blank
document.body.innerHTML = thePage.replace(replacableCode,'');
If you want to identify divs with that particular data attribute, you can use a data-attribute selector. In the example below, I've used a button and click event to make the demo more visual, but in the console the only line you'd need would be:
$('div[data-entry-status="declined"]').remove();
$(function() {
$("#testbutton").click(function() {
$('div[data-entry-status="declined"]').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div id="x">Some other div</div>
<button type="button" id="testbutton">Click me to test removing the div</button>
See https://api.jquery.com/category/selectors/attribute-selectors/ for documentation of attribute selectors.
P.S. Your idea to paste some raw HTML into the jQuery constructor and then execute "remove" on it cannot work - you're telling jQuery to create an object based on a HTML string, which is, as far as it's concerned, a new set of HTML. It does not try to match that to something existing on the page, even if that exact HTML is in the DOM somewhere, it pays it no attention. It treats what you just gave it as being totally independent. So then when you run .remove() on that new HTML...that HTML was never added to the page, so it cannot be removed. Therefore .remove() has no effect in that situation.
I have my website in English but want to show it in Spanish when page loads. So, I got a script from Google Translate that I put in my header file but I need to append some #googtrans(en|fr) at the end of every URL. What I've done so far is:
$(document).ready(function () {
$('a').each(function () {
this.href += '#googtrans(en|es)';
})
});
But a problem with this code is, it is blocking my popups and bootstrap dropdowns.
Is there any simple way to put that trailing string to every URL on page load.
Filter out links that have attributes or classes you don't want the hash applied to:
For example:
$('a').not('[data-toggle], [href^="#"]').prop('hash','#googtrans(en|es)');
If selectors in not() aren't enough you can use the more robust filter() method
A more ideal approach would be being able to have classes on your <a> to represent the ones you do want modified.
<a class="translate">
$('a.translate').prop('hash','#googtrans(en|es)');
OR
<div class="translate">
<a>
</div>
$('.translate a').prop('hash','#googtrans(en|es)');
Note that using the hash property achieves the same as concatenating href
Without seeing more of your html it is hard to provide a lot more help
Now you replace with this code all <a> tags.
Best way - it's taking Google Translator block links on other div, like this:
<div id="gtr">
...
</div>
And Script:
$(document).ready(function () {
$('#gtr a').each(function () {
$(this).attr('href', $(this).attr('href')+'#googtrans(en|es)');
});
});
Instead of
this.href += “#googtrans(en|es)”;
Try this:
$(this).attr("href", $(this).attr("href") + "#googtrans(en|es)");
I need to disable a link tags (whose href attribute value starts with log.html) in my html table. I am trying to use string replace to do.
The code line looks approximately like this, str.replace(/log.html...../g,'') where there must be a regex pattern in the place of dots.
All patterns like this,
<a class="log" href="log.html#s1-s1-s1"></a>
<a class="log" href="log.html#s1-s2-s100"></a>
<a class="log" href="log.html#s10-s5-s1"></a>
must be made as,
<a class="log" href="#"></a>
You can use the following to match:
/log.html#[^"]*/g
And replace with #
Code:
str.replace(/log.html#[^"]*/g,'#')
See DEMO
What you are looking for is string.match(). This function returns an array of the match and any captured groups. You could test all your links with something like this:
$('a').each(function() {
href = $(this).attr("href");
if(href.match(/^log\.html/)) {
$(this).attr("href", "#");
}
});
Fiddle
This regex pattern seems to work given that the url is accessable as a string. This can easily be accomplished with jQuery.
str.replace(/log\.html.*/g,'#')
Since href and ".." are always available in a link, i would use a simple
/href=".+"/g
DEMO
Okay - So this might be really simple but I'm pretty new to anything outside of HTML and CSS so I thought it's time I ask :)
So what I want to do is take the contents from a new attribute and add it to the href attribute.
What I have:
<div id="testDiv">
LINK
</div>
$('#testDiv a').attr('href',newAttr+'.extension');
And the outcome I want is:
<div id="testDiv">
LINK
</div>
Am I missing something really obvious here or am I miles away?
Any help would be great!
Thanks,
Nick
*EDIT - I was missing an equals sign in this post, not my actual code - Rookie :)
You can also use attr() to get the value of an attribute:
$('#testDiv a').attr('href', function (i, attr) {
return $(this).attr('newAttr') + '.extension'
});
Btw, you're missing = inside your HTML markup:
LINK
// ----------------------------- ^ here
Fiddle Demo
EDIT: i is the index position of your anchor in the set of anchors inside div with id testDiv, so in your case it'll be 0 since only one anchor there. In this case, i is not compulsory since you don't need to use it at all.
In the other hand, attr will return the old href value of your anchor. This one is also not needed here since you need the value of newAttr not the href value, so actually you can just leave both of them as blank:
$('#testDiv a').attr('href', function () {
return $(this).attr('newAttr') + '.extension'
});
You need to use the a variant of the attribute setter which takes a function as a handler callback
$('#testDiv a').attr('href', function (i, attr) {
return $(this).attr('newAttr') + '.extension'
});
Demo: Fiddle
Aren't you just missing the equal sign for the newAttr?
<div id="testDiv">
LINK
</div>
should be
<div id="testDiv">
LINK
</div>
I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)