I'm trying to set up a web page that contains links to pages that have Disqus comments on them. There is specific guidance on adding a comment count to a link that Disqus provides, but it's not great. You are limited to using an <a> element, and it replaces the text of the hyperlink with new text.
So, if I create a hyperlink like this on my site:
linktext
after the page loads, it looks like this:
<a class="link-processed" href="http://mysite.com/posts/1234#disqus_thread">
(1 and 0)
</a>
(note that, by default, the replacement text would be "1 comment and 0 reactions" but I have modified the default text to return just the numbers, in brackets.)
When the text of the hyperlink is "(0 and 0)" I'd like to hide the link. When it is anything else, I'd like to replace the text of the link with an image link (little speech bubble or similar.)
I am thinking that the way to do this might be to use a couple of classes. I'll apply the first class (hidelink) by default, and use javascript to apply the second class to the <a> element.
However, now I'm stuck. Javascript is not my native domain. This seems like it should be a straightforward task, though?
What are your browser requirements? If you're using IE8+ (or most other browsers) you could use querySelectorAll or getElementsByClassName to get all processed links and then check if its text match your condition:
var elems = document.querySelectorAll('.link-processed');
for(var i = 0, size = elems.length; i < size; i++)
{
if(elems[i].innerText === "(0 and 0)")
{
//0 and 0. Do something
}
}
Alternatively, if you're using jQuery, you could simply select all elements that contain "0 and 0", using the pseudo class :contains:
$("a:contains('0 and 0')")
Related
I work in a system where we have these elements representing a part of an audio clip, and a timeline for the audio that is browsable (click around to play different parts). However, the elements representing the parts of the audio clip does not actually link to the parts of the audio.. (so no "click this to play this part").
I have deducted that it is possible to link to a specific part of the call via for example: http://thelink.com/timeline?startms=%221600326183999%22. And that the elements all have an attribute called "startms", for example:
<div class="segment-item" startms="1600326183999"></div>
Is there any way I could loop through all the elements in the page with the class "segment-item" and add a href="" with the value of their individual "startms" value to the link (http://thelink.com/timeline?startms=%22TheValueHere%22).
Then finally, since I cannot build an addon to my browser for this, would it be possible to make a snipped which can be pasted into the console for easy use when I need it? Any other suggestions to making such a thing be easily accessible for usage without making or using an addon for chrome?
If you want to add the link to the element, you should add it like that
const elements = document.getElementsByClassName("segment-item")
for (element of elements) {
const a = document.createElement("a")
a.href = `http://thelink.com/timeline?startms=%22${element.getAttribute("startms")}%22`
a.innerText = "LINK NAME"
element.appendChild(a)
}
Adding a link based on element properties goes like this
const elements = document.getElementsByClassName("segment-item")
for (element of elements) {
element.innerHTML = `<a href="http://thelink.com/timeline?startms=%22${element.getAttribute("startms")}%22">
Link name
</a>`
}
I have this link on my web page:
Terms and conditions
I want to use Jquery to check whether this specific link is present or not on the web page. I know how to check if text is present on a page, but am struggling a little with links. If it helps, it is only the terms-conditions-mywebsite bit that I need to use (as mywebsite changes depending on who is using the site).
The class is footer so I have tried $('.footer:contains("terms-conditions") but this doesn't seem to work. Any pointers would be appreciated, thanks so much :)
Edit: I need to check that the actual specific contents of this links is present, rather than the text 'Terms and conditions'
You should check the value of href attribute. You can use Attribute Contains Selector [name*=”value”] which select elements that have the specified attribute with a value containing a given substring:
The following should work:
if($('a[href*=terms-conditions]').length){
//exist
}
OR: Check the link string directly
if($('a:contains("Terms and conditions")').length){
//exist
}
I would look at doing this with Javascript, as it's very straightforward and means you are not reliant on JQuery should you wish to remove JQuery from the site at a later date.
// get <a> elements
var links = document.getElementsByTagName('a');
// loop through each <a>
for (var i = 0; i < links.length; i++) {
// get each href
var hrefs = links[i].getAttribute("href");
// check href against the one you want
if (hrefs == "https://www.google.com") {
// check content of link
console.log('link content:', links[i].innerHTML)
}
}
I'm having some trouble understanding how to use nested selectors in jQuery. I'm parsing a list of classes from my university and I want it to let me know if a class I want is open. However, the website doesn't use css AT ALL, so the only way of identifying the class I want is open is to read the color attribute of the font tag.
Here's the block of HTML I'm trying to read
<TD><FONT FACE='Arial' SIZE='-1' COLOR='Black'>nameOfClass</TD>
Here's how am I'm trying to read it, and display an alert if the font tag attribute color of nameOfClass is "Black", which means its open. It's nasty but its the only way I can tell if the class is available or not.
function main() {
$(document).ready(function(){
if $("td").text()=="nameOfClass"
if $(this "font").attr("COLOR")=="Black" {
alert("It actually works!");
}
});
I never get an alert when I run this though. I'm pretty sure its my syntax, it's been a long while since I did any sort of coding so I might be making some stupid mistake.
You can use .children. But in order for your code to work, you have to iterate over all td elements, not just compare the text value of the first one:
$("td").each(function() {
if($(this).text() === 'nameOfClass' &&
$(this).children('font').attr('color') === 'Black') {
alert("It actually works!");
}
});
Otherwise, $("td").text()=="nameOfClass" only tests whether the text of the first td element in the page is "nameOfClass", which is certainly not what you want. You want to find all td element which contain that string.
You could do it much simpler if you'd directly select all font elements whose color attribute has the value "Black", with the attribute selector. Then you filter out the ones that don't contain the class name and count how many elements are left over. If none, then the class is not open.
var classIsOpen = $('font[color="Black"]').filter(function() {
return $(this).text() === 'nameOfClass';
}).length > 0;
You only need to do an exact comparison of the class name if it could occur as part of an other name, e.g. "Web" and "Advanced Web". If that's not the case, you can make the code even shorter, with the :contains selector:
var classIsOpen = $('font[color="Black"]:contains("nameOfClass")').length > 0;
When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.
Note: I need the design panel, I know its possible to remove it but this is not the case :)
It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.
Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.
Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:
<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">
How can I accomplish this with javascript?
I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.
public string Strip(string text)
{
return Regex.Replace(text, #"<(?!br[\x20/>])[^<>]+>", string.Empty);
}
Any kind of help is appreciated alot
Does this do what you want? http://jsfiddle.net/smerny/r7vhd/
$("body").find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
Basically select everything except a, img, br and replace them with their content.
Smerny's answer is working well except that the HTML structure is like:
var s = '<div><div>Link<span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
console.log($s.html());
The live code is here: http://jsfiddle.net/btvuut55/1/
This happens when there are more than two wrapper outside (two divs in the example above).
Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.
This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.
A working solution is simple: loop from the most inner element towards outside:
var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
var e = $elements[i];
$(e).replaceWith(e.innerHTML);
}
The working copy is: http://jsfiddle.net/btvuut55/3/
with jQuery you can find all the elements you don't want - then use unwrap to strip the tags
$('#container').find('*:not(br,a,img)').contents().unwrap()
FIDDLE
I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:
// the following regex matches the good tags with attrinutes an inner content
var ptt = new RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
var input = "<this string would contain the html input to clean>";
var result = "";
var match = ptt.exec(input);
while (match) {
result += match;
match = ptt.exec(input);
}
// result will contain the clean HTML with only the good tags
console.log(result);
I'm struggling to decipher a way to remove several specific href elements which contain no IDs and are children of individual parents with no IDs.
The best I can manage is identifying the four offending, out of 8 or 9 href tags (and the number may vary), by a specific word within the URL itself. For this, I do the following:
<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
if(ptn.exec(xx[i])){
alert(xx[i]);
}
}
</script>
Of course all this gives me is the four specific URLs within the href where "=media" is present. Now, somehow, I need to be able to remove either these href elements, or their parent elements (which happen to be unordered list tags). It's not until I get a level higher (table cell) that I gain access to an element ID, or anything distinguishing besides a particular word within the URL itself.
I'm open to any approach at this point - PHP may be an option (I really haven't explored this yet), but for this, javascript was my first logical choice. I can't tamper with the page that generates the links directly, only a secondary page which gets included at page load time.
Any pointers on how to solve this??
======================== final solution =====================
<script language=javascript>
var xx = document.getElementById('theID').getElementsByTagName('a');
var ptn=/\=media/;
for(var i=0; i<xx.length; i++) {
while(ptn.exec(xx[i].href)){
alert(xx[i]);
xx[i].parentNode.removeChild(xx[i]);
}
}
</script>
You don't need the ID to remove an element. You only need a reference to the element (which you seem to have).
instead of this:
alert(xx[i]);
try this:
XX[i].parentElement.removeChild(xx[i]);
You can call removeChild() on the parent element, like so:
xx[i].parentNode.removeChild(xx[i]);
As a side note, your regular expression isn't being executed on the href property. Change your if statement to:
if(ptn.exec(xx[i].href)){
var parent = xx[i].parentNode;
parent.removeChild(xx[i]);
http://www.onlinetools.org/articles/unobtrusivejavascript/chapter2.html has some nice examples of similar operations (scroll down).