Insert space into html tag - javascript

I am using window.open('data:application/vnd.ms-excel,' html) to export an HTML table to Excel. I pass the HTML as a string and it works fine.
But I found problem when trying to add a style attribute. I had to change, for example, <th> to <th style="background-color:cornflowerblue"> but the space between th and style disappears and I get <thstyle="background-color:cornflowerblue">. If it was a space in innerHTML, would be fine, but in this case I can't use .

The way you are describing is not really the right way to do it.
You would need to set an attribute style with its value by using JavaScript
Since there isn't much you supplied in order to base my answer on that, you'd have to use the following DOM element: setAttribute()
Here's how it's done:
document.getElementById("yourID").setAttribute("style", "color: yourColor;");
Keep in mind that the above selector is selecting elements by their ID. You can also do that by TagName and instance just like here: https://www.w3schools.com/jsref/met_element_setattribute.asp

Related

How to remove/add html tag in ng-repeat

is it possible to remove/add the html tag dynamically with condition in the javascript?
https://jsfiddle.net/kimsoon/Ldy9xhjt/3/
Example i need to remove the number 2 th column when button is clicked, insert back again when button is clicked. I have using this but does not work.
angular.element(document).find('.dataTable tfoot').remove($scope.items);///to remove
angular.element(document).find('.dataTable thead').prepend($scope.items);//to add
According to the Angular documentation on angular.element().find():
Note: Keep in mind that this function will not find elements by tag
name / CSS selector. For lookups by tag name, try instead
angular.element(document).find(...) or $document.find(), or use the
standard DOM APIs, e.g. document.querySelectorAll().
So, angular.element(document).find(...) can only be used lookup by tag name not class name.
Therefore, your code is not working because your .find() is not returning the element(s) you expect it to (in fact it's not returning any).
Use the DOM method getElementsByClassName to select using class name:
const dataTable = angular.element(document.getElementsByClassName("dataTable"));
Then you can perform your prepends or removals on the wrapped angular dataTable element:
dataTable.remove($scope.items); //to remove
dataTable.prepend($scope.items); //to add

Use JavaScript to rewrite CSS with class and tag at the same time

I am able to easily change the style or the tag of an element based on certain criteria using JavaScript:
document.getElementsByTagName("mainclass")[0].style.color:#ffffff;
However, is there a way to do this is the style contains multiple classes and a tag like so
.mainclass .secondaryclass div td {
color: #000000;
}
The following is not working for me so im sure there is a totally different way of doing it:
document.getElementsByTagName(".mainclass .secondaryclass div td")[0].style.color:#ffffff;
...
The other option if easier is to figure out how to use JS to embbed a external style sheet (and not at the end of head, just where the JS code is thats where the CSS should go)
Thanks!
getElementsByTagName does not accept CSS selector syntax. You're looking for querySelectorAll but you'll have to iterate over the returned list to assign the style, and it's not completely supported across browsers.
...which is why everyone uses jQuery.
Example, assuming you want to modify just the first matched element:
document.querySelectorAll(".mainclass .secondaryclass div td")[0].style.color = '#ffffff';
Note the change from : to =, and wrapping the color value in quotes. JavaScript has different syntax from CSS; I suggest that you take some time to learn it.

:contains incorrectly selecting child elements

Currently I'm trying to select a link element with the jQuery :contains selector. This works when the contents of the link is just text. but it seems that when the element contains other HTML elements the :contains selector selects a child element instead. Example
HTML:
<b> two</b> this not bold <b>This</b> is a bold Link
from that html, I'm trying to select the link using this selector
jQuery:
var selector = "a:contains('<b> two</b> this not bold <b>This</b> is a bold Link')";
var returnObj = $(selector);
Instead of getting one returned object (the link), jQuery returns three objects:
the first bold element
the text this is not bold
the second bold element
the problem isn't the single quotes within the contains(), as I've tried with and without them.
This is just a simplified example of what I'm trying to do. In reality, I'm dynamically creating selectors based off of a link object a user clicks. I then store that selector in a database for use later (for my app to display content related to that link). Since I can get the contents of the link, I figured I'd just use a:contents() if the link doesn't have an id.
based off of these pages, I seem to have my syntax right:
http://docs.jquery.com/Tutorials:How_to_Get_Anything_You_Want_2
http://api.jquery.com/contains-selector/
Thoughts on how to get the link object returned? Thanks!
hope this isn't too stupid a question, I'm new to JS and jQuery.
As mentioned, :contains() is meant to select by text content only, not inner HTML.
If you must match the a element based on that text, strip out the <b> tags:
var selector = "a:contains(' two this not bold This is a bold Link')";
Otherwise, see if you can simplify this selection by using a contextual selector (e.g. select based on its surrounding elements, parents, siblings, etc), or assign it a class and select by that class instead.
On a side note, I'd consider this yet another jQuery bug (could be a parsing error in Sizzle). In your situation, :contains() is not supposed to return or create any elements; it's supposed to return no matches simply because the selector doesn't match your a element. I suspect what it's doing instead is treating the <b></b> tags as new elements, and creating them on the fly along with your a element, which is wrong because the tags are inside the argument string and meant to be taken literally...
First of all your selector text does not match the actual text in your html.
The selector includes the this not bold which is not present in the html.
Most importantly the :contains works with the text only.. so you should check for
$("a:contains('two this not bold This is a bold Link')");
It is a very inefficient way though, and you should better add a class to the elements you want to target and use that for targeting..

JavaScript String .replace method is replacing all my content?

I have successfully implemented finding and replacing some text with something else in the following way:
$(".class").html($(".class").html().replace(/\text\b/g, '<span class="newclass newclass2">new text</span>'));
When I apply this to my element 'class' it finds all the 'text' and replaces with 'new text' and everything relating to the new classes.
However, if I have more than one element on the page with the same class, it replaces all the classes with whatever text is in the first class.
For example, if my first class has the content "Hello everyone", when the script is applied to this class, it works fine. Any subsequent class of the same name is then replaced with "Hello everyone". These also have the function applied in the same way as the first occurrence of that class.
IE, it applies the script, then replicates this in every single class of the same name on the page.
I do not understand why it would do this, and rather renders the function pointless in many ways if it can't be used to change text throughout different sections without setting up new scripts and different classes.
Hopefully there is something simple at work here that I am not aware of, any help would be much appreciated.
Many thanks
Richard
That is the nature of class selectors--the .html(...) will replace the HTML of everything that matches the .class selector.
If you want to replace text in each individual .class element, you can use the .each function. (There are probably jQuerier ways, too.)
$(`.class`).each(function(n, el) {
var myHtml = $(this).html();
myHtml = mungeIt(myHtml);
$(this).html(myHtml);
});
If you want to select only an individual .class element, then you either (a) don't really want to be using classes, but IDs, or (b) need to understand enough of your structure or the context you wish to operate in to select only the targeted DOM element.
(And hope the structure or context doesn't change without a corresponding code update.)
You're specifying a class with the jQuery selector $(".class") That's what the period indicates. jQuery has a ton of selectors to choose from. A list is provided in the documentation here: http://api.jquery.com/category/selectors/
Also, I'd look at http://api.jquery.com/hasClass/ for your problem as you could then use if...then statements to not run into others
Dave is right about needing to use the .each method. We need to loop through each element at a time because .html() will only return the first element when there are multiple matches.
Try:
$('.class').each(function() {
$(this).html($(this).html().replace(/someWord/g,'withAnother'));
});

Parsing HTML in plain text or XML form

I have 2 questions:
1st Question: Can a HTML element have more than one class(be part of more than one class)?
<p class="paragraphClass" class="highlightClass"/> // is that allowed?
2nd Question: Is there a javascript HTML parser library or set of default functions that search a string of HTML & give me all the HTML elements that have a specific class? I use AJAX to get HTML from a server(returned as text not XML), I then need to convert all HTML elements that have the class "updatable" to text-area HTML elements.
What do you think would be the easiest way to convert all HTML elements of a specific class to textareas when I have a string of HTML as either text or XML.
1st Question: Can a HTML element have more than one class(be part of more than one class)?
Yes, but like this:
<p class="paragraphClass highlightClass"/>
2nd Question: Is there a javascript HTML parser library or set of default functions that search a string of HTML & give me all the HTML elements that have a specific class?
The dead-simplest way to do this is with jQuery (surprise, surprise):
var html = 'your html in a string here',
$html = $(html),
$elts = $html.find('.someClassName');
// $elts is a (array-like) jQuery object which
// contains all the elements in the HTML string with class 'someClassName'
See the jQuery selectors API docs for more.
You can have as many classes as you like on any element by seperating them with spaces. eg:
<p class="paragraphClass highlightClass"></p>
Use a library like jQuery to do this.
1) Yes, but your syntax is not correct. You can specify more than one class separated by spaces like:
<p class="paragraphClass highlightClass"/>
2) You could just insert your HTML into the DOM using some elements .innerHTML property. That element could have display: none; so that it doesn't affect your page. Then you can use normal DOM methods on them like document.getElementByClassName('updatable'); Note that getElementByClassName() is not defined in IE so you have to write your own that selects by tagName and then iterates through them matching the classes, or use a framework like jQuery.
there is always jquery. You can use the selector to select all the elements with that class and then convert it to a textarea. Sounds like you want to convert it to edit that paragraph.
$(".paragraphClass").each(function{
$(this).replaceWith("<textarea>"+ $(this).text() +"</textarea>");
})
http://jsfiddle.net/bQgN3/

Categories