How to check if href attribute contains a string? - javascript

I want to get all "a" tags from page, get its "href" attribute and check if in this href is text ".pdf". So I get all a tags into tags variable, then with each() function I check every "a" (as a tag). But code:
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
is not working. Why? Why I can't use indexOf on href? I tried with search() function, but it's also not working.
So I thought - ok, there's something wrong with this href. Lets take it as a text.
But code:
var text = $(tag).text();
console.log(text);
is also not working. Can anybody tell me why?
Code snippet has errors intentionally - to show with what I have a problem.
Thank you in advance.
(function($){
var tags = $('a');
$(tags).each(function() {
var tag = $(this).attr('href')
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
var text = $(tag).text();
console.log(text);
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
Link with ".pdf"
Link without ".pdf"
</html>

No need to for the additional $(tag) when calling indexOf. tag is a string at that point and you don't need to make it a jQuery object. simply call tag.indexOf('.pdf') > 0. For strings you can also use tag.includes('.pdf') or you go for tag.substr(tag.length - 4, 4) === '.pdf' to make it even more precise.

Related

Hide element using JavaScript

What I want is to hide certain element using Javascript. Specifically, I want this element showed only if the URL contains the text 'cli'. I tried that using next code
var regex = window.location.href;
if(regex.indexOf('cli')>-1){
$(window).load(function() {
$("[routerlinkactive]")[1].remove();
});
}
The routerlnkactive parts works separatedly. That is, if no if statement is written, it is always removed. But I want that to work only with that URL. How could I do that?
Doesn't seem to be working neither with xxx.html or with xxx.html?cli=30
Thank you.
try using the indexOf() function. So something like
var regex = window.location.href;
if(regex.indexOf('cli')>-1){ //if cli is there
$("[routerlinkactive]")[1].hide(); //hide
}
It will return -1 if not found, and will return the string position number if found (starting at 0).
Also, you should use .hide() to hide, not remove.
UPDATE:
since you are saying its still not working, i have just checked, and this works:
var regex = "xxxxxx.com?cli=50";
if(regex.indexOf('cli')>-1){
alert(true);
}else{
alert(false);
}
So replace alert() with the hide() function and make sure the html is correctly referenced (even though you said that was working okay?). And the value of regex should be window.location.href.
Try adding and removing 'cli' and youll see the difference.
Remove() is not the right choice, that will remove the element from the DOM.
Use hide() and show().
$(document).ready(function(){
//Hide your element by default on page load
$("[routerlinkactive]")[1].hide();
if(window.location.href.indexOf("cli") > -1) {
//If URL has "cli" then show that element.
$("[routerlinkactive]")[1].show();
}
});
Reference of indexOf()

How do I give an ID to part of the contents of a <title> tag?

I have a title tag that looks something like this:
<title>My Page Title - Photo #3</title>
I want to use JavaScript to change the numeric part of it, without having to hard code the "My Page Title - Photo #" string which is generated server side.
I tried wrapping the number in a span so that I could change the contents of the span:
<title>My Page Title - Photo #<span class="photoid">3</span></title>
But it seems HTML is not allowed in the title tag. I'd really like to pursue the class approach if possible as that would allow me to use a line of jquery such as this:
$('.photoid').html(new_photoid);
Did I mention that the photoid appears in several places on the page, which is why I want to be able to use this oneliner to change them all at the same time? For example:
<p>A paragraph also containing the number <span class="photoid">3</span></p>
A title can only have text, so you need to parse it out.
document.title = document.title.replace(/\d+$/, "new value");
title can't be set like that,
it's not a child of .html
some thing like
var num = 3;
document.title = "foo "+num
to set the title, then reuse num for these photoids.
Use the jQuery onDocumentReady syntax:
$(function () {
var elements = $('.contains_photoid');
elements.html(elements.html().replace("3", "4"));
$(document).attr('title', $(document).attr('title').replace("3", "4"));
});
You can't see the title change in this example, but that is the syntax. See Changing the page title with Jquery
The "3" and "4" can be changed to anything, so you can create the page with a unique character string in place of the real ID in order to easily replace it if it appears in text with numbers already in it.
http://jsfiddle.net/ZmXj5/1/
Javascript
var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;
See this fiddle for proof: http://jsfiddle.net/xrkhA/
(I used a div content because you can't use title in jsfiddle)
You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');

change part of a link with javascript in a specific div only

Hi I need to edit some links on a page. Using the below code works but causes other problems on the page. I need the code to only affect elements with a certain input id. I also can't just replace the links as a query will be dynamically added to the end of each link. So in summary i just need to replace parts of all links with an input id "btnViewDetails". Any help would be great I'm very stuck. Cheers
<script language="javascript">
document.body.innerHTML = document.body.innerHTML.replace(/JobSeekers/g,'mobile');
document.body.innerHTML = document.body.innerHTML.replace(/JobPositionDetail.aspx/g,'JobPositionDetail_Mobile.aspx');
</script>
var someVariable = document.getElementsByClassName('btnViewDetails');
(you should use class instead of ID, if it is not a unique value).
someVariable is now an array holding all elements with class name btnViewDetails.
Now replace the text you want to replace only on the href values of you elements (you will have to loop over them):
for (i = 0; i < someVariable.length; i++) {
someVariable[i].href // do your replaces here
}

Split value of a html tag

I would like to split some content from an "a" html tag. I was starting over with jquery. My code is like this but it is not working:
$("a.uribb").each(function() {
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).append(+id+);
});
​
And the HTML tag is this:
<a href="http://dereferer.org/?http://example.com/" target="_blank" class="uribb">
http://example.com/
</a>
I wanted to split out the http://dereferer.org/? part and leave the other there. How could I do this?
Try to use .text() instead of .append() if you want to replace the content. Also, there is no need for the + before and after the id.
You could try this instead:
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).text(id);
Update
Reading through the question again, I'm not sure if you want to replace the content of the a-tag or the the value of the href. In case of the latter, try this:
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).attr("href", id);
Notice
Since jQuery 1.6, it is preferred to use .prop() instead of .attr().
How about that?
$("a.uribb").attr("href", function(i, val) {
return val.substring(val.indexOf("?") + 1);
});​
DEMO: http://jsfiddle.net/zQdL4/
It's interesting but for your markup the following code should also work :)
$("a.uribb").attr("href", function() {
return $.trim(this.innerHTML);
});​
Right, so what you want is this.
<a href="http://example.com/">...
Try this.
$("a.uribb").each(function() {
var indirect_url = $(this).prop("href");
var direct_url = indirect_url.replace("http://dereferer.org/?", "")
$(this).prop('href', direct_url);
});
You could of course do this in fewer lines, but this way it's clear what's going on. Specifically, replace() does not modify the string it operates on.

Extracting text from a HTML to be stored as a JS variable, then to be added to a separate HTML's element

Alrite, I have seen other Questions with similar titles but they don't do exactly what Im asking.
I have 2 x HTML documents, one containing my page, one containing a element with a paragraph of text in it. As-well as a separate .js file
what I want to do is extract this text, store it as a JS variable and then use jQuery to edit the contents of an element within the main page. This is the conclusion I came to but it didnt work as expected, im not sure if it is me making a syntax error or if i am using the wrong code completely:
$(document).ready(function(){
var c1=(#homec.substring(0))
// #homec is the container of the text i need
$(".nav_btn #1").click(function(c1){
$(".pcontent span p") .html(+c1)}
);
});
i know +c1 is most probably wrong, but i have been struggling to find the syntax on this one. thankyou in advance :D
var c1=(#homec.substring(0)) will throw an error because #homec is not a valid variable name, is undefined, and does not have a property function called substring. To get the html of an element with an id of homec, use the html method:
var c1 = $("#homec").html();
c1 should not be an argument of the click function because it is defined in the parent scope. +c1 is unnecessary because you do not need to coerce c1 to a number.
If you are trying to add content to the end of the paragraph, use the append method:
$(".pcontent span p").append(c1)
That means you should use this code instead:
$(document).ready(function() {
var c1 = $("#homec").html();
$(".nav_btn #1").click(function() {
$(".pcontent span p").append(c1)
});
});
P.S. Numbers are not valid ID attributes in HTML. Browsers support it, so it won't make anything go awry, but your pages won't validate.
Try this:
$(".nav_btn #1").click(function(c1){
var para = $(".pcontent span p");
para.html(para.html() + c1);
});
The JQuery text() function will allow you to get the combined text contents of each element in the set of matched elements, including their descendants. You can then use the text(value) function to set the text content of your target paragraph element. Something like this should suffice:
$(document).ready(function() {
var c1 = $("homec").text();
$(".nav_btn #1").click(function() {
$(".pcontent span p").text(c1);
});
});
See the JQuery documentation for more details on the text() function. If you need to capture the full structure of the other document, then try the html() function instead.

Categories