简体   繁体   中英

Identifying elements in messy (but predictable) HTML code

I want to develop a very simple userscript for a web app, which will mainly insert some elements and CSS. I can't make changes to the source code. The HTML code is kind of messy: It's table-based, most elements don't have IDs, not all of them have useful classes, there are lots of useless elements nested inside other elements, etc. In short, no element is clearly identifiable.

The good things are that the layout is always the same, so the structure is predictable, and there will be no changes to the source code for the foreseeable future (probably never). Taking these things into consideration, the only solution I could think of was to identify the elements through their messy context (for example, one element of interest can be identified by $("div table table > tr > td"); ). If I follow this idea, things will work, but it won't exactly radiate quality.

So, is there a better way to achieve this?

I recommend watching this talk on "effort-less styles", which could also be used for js. https://vimeo.com/101718785

Here is an article about the same topic http://www.smashingmagazine.com/2013/08/20/semantic-css-with-intelligent-selectors/

If you are wanting to relieve a bit on code quality, by means of not having a whole lot of selectors with a many child elements, putting the selections you would like into some variables to refer to. For example:

Instead of having to write

$("div table table > tr > td").on("event", function(){ code });

Save the selectors into a variable, especially if they are used more than once.

var $a_Variable = $("div table table > tr > td");

And then reference the variable as a selector. You could also add your classes to them to if you cannot edit your html code, granted if you have access to define css styling.

$(a_Variable).on("click", function(){ $(this).addClass('.some_class'); });

Defining variables is a good way to save on rewriting the same thing multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM